namespaces

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Jul 31 07:14:29 EDT 2005


On Sun, 31 Jul 2005 12:44:46 +0200, Paolino wrote:

> I show you a piece of code I need to define a function:
> 
> import string
> all=string.maketrans('','')
> badcars=all.translate(all,string.letters+string.digits)
> table=string.maketrans(badcars,'_'*len(badcars))
> def translate(text):
>    return text.translate(table)

Or do this:

def translate(text):
    import string
    all=string.maketrans('','')
    badcars=all.translate(all,string.letters+string.digits)
    table=string.maketrans(badcars,'_'*len(badcars))
    return text.translate(table)

No pollution.

> What I'm needing as a global (in globals() or at the module level or in 
> the module namespace) is 'translate'.The rest of bindings (all,badcars 
> and table) is something which is 'polluting' the module namespace.

Then after you are finished with the bindings, delete them:

import string
all=string.maketrans('','')
badcars=all.translate(all,string.letters+string.digits)
table=string.maketrans(badcars,'_'*len(badcars))
def translate(text):
    return text.translate(table)
# clean up the temporary variables so as to prevent namespace pollution
del string; del all; del badcars; del table


-- 
Steven.




More information about the Python-list mailing list