newbie: self.member syntax seems /really/ annoying
Alex Martelli
aleax at mac.com
Wed Sep 12 13:05:41 EDT 2007
Chris Mellon <arkanes at gmail.com> wrote:
...
> This is terrible and horrible, please don't use it. That said,
> presenting the magic implicit_self context manager!
...which doesn't work in functions -- just try changing your global
code:
> with implicit_self(t):
> print a
> print b
> a = 40
> b = a * 2
into a function and a call to it:
def f():
with implicit_self(t):
print a
print b
a = 40
b = a * 2
f()
...even with different values for the argument to _getframe. You just
can't "dynamically" add local variables to a function, beyond the set
the compiler has determined are local (and those are exactly the ones
that are *assigned to* in the function's body -- no less, no more --
where "assigned to" includes name-binding statements such as 'def' and
'class' in addition to plain assignment statements, of course).
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).
You could try defeating the fundamental optimization that stands in your
way by adding, say,
exec 'pass'
inside the function-needing-fakeouts -- but we're getting deeper and
deeper into the mire...;-)
Alex
More information about the Python-list
mailing list