Method Underscores?

Lonnie Princehouse finite.automaton at gmail.com
Thu Oct 21 23:18:58 CEST 2004


It's extremely common for Python newbies to accidentally overwrite
the names of important things.  I see stuff like this all the time:

    list = [1,2,3]
    str = "Hello world"

This sort of accidental trampling would be even more frequent without
the underscores.


And, to play devil's advocate, there are probably a dozen ways to 
hack around the underscores, for those who don't like them:

class __silly__(type):
    def __new__(cls, name, bases, dct):
        # incomplete list - just enough for a demo
        magic_functions = ['init','len','str']
        for f in [x for x in magic_functions if x in dct]:
            dct['__%s__' % f] = dct[f]
        return type.__new__(cls, name, bases, dct)
__metaclass__ = __silly__

class Bar:
    def init(self):
        print "init Bar instance"
    def str(self):
        return "Bar str method"
    def len(self):
        return 23

f = Bar()
>>> "init Bar instance"
str(f)
>>> "Bar str method"
len(f)
>>> 23




"Chris S." <chrisks at NOSPAM.udel.edu> wrote in message news:<9dIdd.3712$EL5.3057 at trndny09>...
> Is there a purpose for using trailing and leading double underscores for 
> built-in method names? My impression was that underscores are supposed 
> to imply some sort of pseudo-privatization, but would using 
> myclass.len() instead of myclass.__len__() really cause Python 
> considerable harm? As much as I adore Python, I have to admit, I find 
> this to be one of the language's most "unPythonic" features and a key 
> arguing point against Python. I've searched for a discussion on this 
> topic in the groups archives, but found little. What are everyone's 
> thoughts on this subject?



More information about the Python-list mailing list