namespaces

Paolino paolo_veronelli at tiscali.it
Mon Aug 1 19:39:30 EDT 2005


Paolino wrote:


> Now this is the non polluting version :
> 
> class translate:
>    import string
>    all=string.maketrans('','')
>    badcars=all.translate(all,string.letters+string.digits)
>    @staticmethod
>    def __call__(text,table=string.maketrans(badcars,'_'*len(badcars))):
>      return text.translate(table)
> translate=translate()
> 

## As now a good solution I got (from a RexFi hint in IRC) is via
## classmethods as it doesn't use free variables.
import string
class translate(object):

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

translate=translate.translate

#### Refactoring again this is the more elegant

import string

class translateUnderscore(object):
    all=string.maketrans('','')
    badcars=all.translate(all,string.letters+string.digits)
    table=string.maketrans(badcars,'_'*len(badcars))
    def __new__(cls,text):
      return text.translate(cls.table)

#### Which allows for part-function reuse:

class translateQuestionmark(translate):
    table=string.maketrans(translate.badcars,'?'*len(translate.badcars))

translateUnderscore('problem at pytypus.org')
translateQuestionmark('problem at pytypus.org')

###############

An inefficency for these solutions is the further indirection to lookup 
attribute 'table' in the call (cls.table). (From RexFi also)



Regards Paolino

		
___________________________________ 
Aggiungi la toolbar di Yahoo! Search sul tuo Browser, e'gratis! 
http://it.toolbar.yahoo.com



More information about the Python-list mailing list