[Tutor] "farkadoodle" or: unique global names, was Re: Data persistence problem

Peter Otten __peter__ at web.de
Sat Jun 22 09:04:35 CEST 2013


Jim Mooney wrote:

> dictnumfarkadoodle = listnumfarkadoodle = setnumfarkadoodle = 0
> # Since these are global I'm using words not likely to be duplicated
> until I figure a different way and
> # replace 'farkadoodle' with '' ;')

Name clashes are generally not a problem if 

(1) you keep module size manageable and 
(2) use descriptive names

I'd suggest

_dictname_index

or

_makeseq_dictname_index


If you want to follow the generator approach you can use default arguments:

>>> from itertools import count
>>> def make_nextname(template):
...     return map(template.format, count()).__next__
... 
>>> f = make_nextname("farkadoodle{}")
>>> f()
'farkadoodle0'
>>> f()
'farkadoodle1'
>>> f()
'farkadoodle2'
>>> def make_seq(text, type, next_setname=make_nextname("set{}")):
...     if type == set:
...             print(next_setname(), "=", set(text.split()))
...     else:
...             raise ValueError("unsupported type")
... 
>>> make_seq("alpha beta gamma", set)
set0 = {'alpha', 'beta', 'gamma'}
>>> make_seq("alpha beta gamma", set)
set1 = {'alpha', 'beta', 'gamma'}
>>> make_seq("alpha beta gamma", set)
set2 = {'alpha', 'beta', 'gamma'}

Here's an alternative implementation of make_nextname() which may be easier 
to understand:

>>> def make_nextname(template):
...     counter = -1
...     def nextname():
...             nonlocal counter
...             counter += 1
...             return template.format(counter)
...     return nextname
... 
>>> f = make_nextname("foo{:03}")
>>> f()
'foo000'
>>> f()
'foo001'
>>> f()
'foo002'

This technique of nesting a function inside another function ("closure") can 
also be used on make_seq directly:

def make_make_seq():
    set_index = 0
    ...
    def make_seq(text, type):
        nonlocal set_index
        if type == set:
            print("set%s" % set_index, "=", set(text.split()))
            set_index += 1
        ...
    return make_seq

make_seq = make_make_seq()
make_seq("a b c", set) # set0 = {'c', 'b', 'a'}
make_seq("a b c", set) # set1 = {'c', 'b', 'a'}




More information about the Tutor mailing list