On Thu, 27 Nov 2008 08:32:12 -0800, Emanuele D'Arrigo wrote:

> On Nov 27, 5:00 am, Steven D'Aprano
> <[EMAIL PROTECTED]> wrote:
>> Refactor until your code is simple enough to unit-test effectively,
>> then unit-test effectively.
> 
> Ok, I've taken this wise suggestion on board and of course I found
> immediately ways to improve the method. -However- this generates another
> issue. I can fragment the code of the original method into one public
> method and a few private support methods. But this doesn't reduce the
> complexity of the testing because the number and complexity of the
> possible path stays more or less the same. The solution to this would be
> to test the individual methods separately, 

Naturally.


> but is the only way to test
> private methods in python to make them (temporarily) non private? I
> guess ultimately this would only require the removal of the appropriate
> double-underscores followed by method testing and then adding the
> double-underscores back in place. There is no "cleaner" way, is there?

"Private" methods in Python are only private by convention.


>>> class Parrot:
...     def _private(self):  # private, don't touch
...             pass
...     def __reallyprivate(self):  # name mangled
...             pass
...
>>> Parrot._private
<unbound method Parrot._private>
>>> Parrot.__reallyprivate
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: class Parrot has no attribute '__reallyprivate'
>>> Parrot._Parrot__reallyprivate
<unbound method Parrot.__reallyprivate>

In Python, the philosophy is "We're all adults here" and consequently if 
people *really* want to access your private methods, they can. This is a 
Feature, not a Bug :)

Consequently, I almost always use single-underscore "private by 
convention" names, rather than double-underscore names. The name-mangling 
is, in my experience, just a nuisance.



-- 
Steven
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to