newbie: self.member syntax seems /really/ annoying
attn.steven.kuo at gmail.com
attn.steven.kuo at gmail.com
Thu Sep 13 11:10:46 EDT 2007
On Sep 12, 10:05 am, al... at mac.com (Alex Martelli) wrote:
...
> 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...;-)
What about abusing 'import' like this:
def f():
with implicit_self(t):
sys.modules['__the_mire__'] = t
from __the_mire__ import a, b
print a
print b
a = 40
b = a * 2
If the list of attributes is long then
'import' can save some typing compared to
a = self.a
b = self.b
...
z = self.z
--
Regards,
Steven
More information about the Python-list
mailing list