newbie: self.member syntax seems /really/ annoying

Carl Banks pavlovevidence at gmail.com
Wed Sep 12 16:52:54 EDT 2007


On Sep 12, 1:05 pm, al... at mac.com (Alex Martelli) wrote:
> Making, say, 'a' hiddenly mean 'x.a', within a function, requires a
> decorator that suitably rewrites the function's bytecode... (after
> which, it WOULD still be terrible and horrible and not to be used, just
> as you say, but it might at least _work_;-).  Main problem is, the
> decorator needs to know the set of names to be "faked out" in this
> terrible and horrible way at the time the 'def' statement executes: it
> can't wait until runtime (to dynamically determine what's in var(self))
> before it rewrites the bytecode (well, I guess you _could_ arrange a
> complicated system to do that, but it _would_ be ridiculously slow).


How about this?  The decorator could generate a bytecode wrapper that
would have the following behavior, where __setlocal__ and
__execute_function__ are special forms that are not possible in
Python.  (The loops would necessarily be unwrapped in the actual
bytecode.)


for sym in sys._getframe(0).f_code.co_varnames:
    if sym == "self":
        continue
    try:
         __setlocal__(sym,getattr(self,sym))
    except AttributeError:
         pass
try:
    __execute_function__()
finally:
    for sym,val in locals.iteritems():
        if sym == "self":
            continue
        if sym in self:
            setattr(self,sym,val)


This wouldn't be that much slower than just assigning local variables
to locals by hand, and it would allow assignments in the
straightforward way as well.

There'd be some gotchas, so extra care is required, but it seems like
for the OP's particular use case of a complex math calculation script,
it would be a decent solution.

I understand where the OP is coming from.  I've done flight
simulations in Java where there are lot of complex calculations using
symbols.  This is a typical formula (drag force calculation) that I
would NOT want to have to use self.xxx for:

FX_wind = -0.5 * rho * Vsq * Sref * (C_D_0 + C_D_alphasq*alpha*alpha +
C_D_esq*e*e)

Even if I'd habitually used "this." in Java, I'd probably skip it in
functions like htis.


Carl Banks




More information about the Python-list mailing list