namespaces

Rob Williscroft rtw at freenet.co.uk
Sun Jul 31 07:16:38 EDT 2005


deelan wrote in news:ve1He.29121$TR5.13328 at news.edisontel.com in
comp.lang.python: 

> Paolino wrote:
> (...)
>> 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. 
> 
> try this:
> 
> ## yourmodule.py ##
> 
> def _setup_table():
>    import string
>    all=string.maketrans('','')
>    badcars=all.translate(all,string.letters+string.digits)
>    return string.maketrans(badcars,'_'*len(badcars))
> 
> TABLE = _setup_table()
> 
> # optional, get rid of _setup_table symbol
> del _setup_table()
> 
> def translate(text):
>    return text.translate(TABLE)
> 

After 3 or 4 iterations I refactored you code to this:

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

    global translate
    def translate( text ):
        return text.translate(TABLE)

    print "First Call! ", # -- Just for demonstration --

    return translate( text )

print translate("If I was ...")
print translate("If I was ...")

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/



More information about the Python-list mailing list