Update locals()

holger krekel pyth at devel.trillke.net
Sun Apr 28 07:52:21 EDT 2002


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()) 

    # ...

# 'indentedcode' basically prepends 'if 1:' so that i
# don't have to write the template without indenting.

Generally i have lots of nice callable objects 
in the 'filters' module. Some must be initialized, some
are stateless. 

#module 'filters' contains *for example*

class access:
    """(stateful) checks filename for a given access-mode.
       the mode string contains a combination
       of 'r' 'w' 'x'. the filter afterwards accepts
       a filename or a string if it is accessable 
       with the given mode"""
    def __init__(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
        self.flags=flags

    def __call__(self, fn):
        return os.access(str(fn),self.flags) and fn

In this case of defining templated methods in a class with
tiny adapters to make use of functions somewhere else
it seems natural to stay in the same exec-context (this case 
class definition), whatever it may be. That's why
i wrote 'indentedcode' to stress the fact.

With the prescribed python-templates you can adapt 
'syntax' to achieve a richer calling interface and 
avoid redundancies in coding. I want to define 
stateful/stateless filters in one place and let 
the filename class offer adapted methods and inherit 
the documentation.  Also see an example at the end on how
you this can be put to use.

Note three things:

- I guess that there are other methods like
  Currying which *might* help here. I don't
  think they provide the same ease, though.

- in the prescribed type of templates 
  i think there is no performance penalty
  as the compiler sees the complete 'def .. : '

- i am a maniac at avoiding redundancies.
  that's the reason i looked for transfering
  matches in re-patterns into something
  useable without noise.

If you really know an easy minimally redundant way 
of expressing the same semantics (above) i am very 
interested.

But i even have two other examples :-) 

regards,

    holger


--

# real world example using the precscribed semantics 
# 
base=filename('/usr/src/cpp')

count = Counter()
resultfilters = AND(isfile, nolink, fnmatch('data*'), count)
recursefilter = access('wx')

for dir, fnlist in base.filterwalk( resultfilters, recursefilter ):
    for fn in fnlist:
        print "  ",fn.relativeto(base)
        ...

print 'processed %d occurences of writable data files' % count.count

# filterwalk is a generator 
# filterwalk_now returns the complete list in one go











More information about the Python-list mailing list