Update locals()

jepler at unpythonic.net jepler at unpythonic.net
Sun Apr 28 09:50:13 EDT 2002


On Sun, Apr 28, 2002 at 01:52:21PM +0200, holger krekel wrote:
> Thanks for the explanations. 
> 
> There is no question that C++-like templates often are
> not needed in python. I regret mentioning C++ because
> it is only a very distant analogy as you pointed
> out precisely. 
> 
> > Please give ONE example which, in your opinion, is best handled
> > with 'exec' without explicit dictionaries rather than in any other way.
> 
> i try to make it short and answer questions (if any of you gurus
> ever have any :-) as needed. Obviously you can always pass explicit 
> dictionaries to exec (globals, locals). That can't be the point. 
> 
> I cite some of my code.
> 
> class filename:
>     """ Abstraction for filename ... """
>     # ...
> 
>     for name in filters._stateful_all:
>         doc=filters.__dict__.get(name,undoc).__doc__.strip()+'\n'
>         exec indentedcode("""
> 
>     def %(name)s (self,*args,**kargs):
>         '''%(doc)s'''
>         return filters.%(name)s (*args,**kargs) (self)
>     """ % locals()) 
> 
>     # ...

I don't quite see what you're doing here, but you might try something like
(given nested scopes) (untested):

    class filename:
	def __getattr__(self, attr):
	    if not hasattr(filters, attr): raise AttributeError, attr
	    filter_func = getattr(filters, attr)
	    ret = lambda *args, **kargs: filter_func(*args, **kargs)(self)
	    ret.__doc__ = getattr(filter_func, __doc__, undoc)
	    #setattr(self, attr, ret)
	    return ret

My version will also work properly if "filters" is extended at runtime with
new attributes... It's reasonbly efficient to construct a function at
runtime with 'lambda', and you can trade time for space by caching the
attribute on the instance once it's been computed once

Of course, given that you always immediately call the instance of the
filters. function, I don't see why you can't simply write

    class filename:
	def access(self, mode='r'):
	    flags=0
	    if 'r' in mode: flags|=os.R_OK
	    if 'w' in mode: flags|=os.W_OK
	    if 'x' in mode: flags|=os.X_OK
	    return access(str(self), self.flags) and self

There's probably some reason which isn't as apparent in this example as
some of the more complex ones you've written, though...

Jeff





More information about the Python-list mailing list