data hiding/namespace pollution
bruno at modulix
onurb at xiludom.gro
Mon Oct 31 09:13:55 EST 2005
Alex Hunsley wrote:
> bruno at modulix wrote:
>
>> Alex Hunsley wrote:
>>
(snip)
>>>
>>> method 1:
>>>
>>> _X - (single underscore) - just cosmetic, a convention to let someone
>>> know that this data should be private.
>>>
>>>
>>> method 2:
>>>
>>> __X - (double underscore) - mangles the name (in a predictable way).
>>> Avoids name pollution.
>>>
>>>
>>> How often does either tend to get used? Personally, I'd be a little
>>> worried about using method 1, because namespace clashes could happen. Is
>>> this overly paranoid?
>>
>> Probably.
>>
>> Note that prefixing names with a single underscore have a 'protected'
>> semantic - which means that such names (well, the objects that are bound
>> to...) can be overriden/extends by child classes.
>
>
> Ah, my mistake, not merely cosmetic then! Thanks.
Well, to be more exact, the point is not that _names can be overriden,
but that, due to name mangling, the following won't work, or, at least,
not as expected:
class Base(object):
def __dothis(self):
print "Base dothis"
def dothat(self):
print "Base dothat"
def run(self):
self.__dothis()
self.dothat()
class Child(Base):
def __dothis(self):
print "__%s_dothis" % self.__class__.__name__
def dothat(self):
print "%s dothat" % self.__class__.__name__
c = Child()
c.run()
(snip)
> Sorry, I wasn't being clear. What I should have said is that I don't
> like the idea of a typo in an assignment causing the assigning of the
> wrong thing.
> e.g. imagine a simple value-holding class:
>
> class Values:
> pass
>
> v = Values()
>
> v.conductoin = 10
>
>
> ... I meant to type 'conduction' in the source but spelt it wrong.
> My value won't be there when elsewhere I refer to the correct attribute:
> "conduction".
>
This kind of mistakes are usually not too hard to spot and not too hard
to correct. You'd have the same problem with a dict (and your Values
class is not much more than a dotted_syntax dict in disguise). BTW,
Pylint or Pychecker would catch this, and most unittests too.
Now if you have a case where this could really matter (like a user's
script), you can then define a more bondage_and_the_whip class with slots.
My overall experience with programming and Python is that keeping it
stupid simple where you can is usually the best approach. Your
__setattr__as_a_typo_catcher solution looks to me like a case of
arbitrary complexification. Better to go with the language than to fight
against it.
My 2 cents...
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list