Reputation: 18296
Suppose I have a python class with a method that's not useful to callers (i.e. it should be private), but it has a few corner cases so I want to do a sanity check on it (i.e. it should be unit tested).
Naively, I expected I could write a doctest:
class Thingy:
...
def __frob(self, val):
"""
>>> Thingy(...).__frob(-2)
1
"""
...
But when I do so I get an error:
AttributeError: type object 'Thingy' has no attribute '__frob'
Which makes sense in hindsight, but isn't very convenient.
Is there a simple way to doctest private methods, besides just making them public?
Upvotes: 2
Views: 1042
Reputation: 1123640
Python doesn't really have private methods. Double-underscore names are mangled; they get the class name (with a leading underscore) prepended to their name. That's because their goal is to help avoid name clashes when subclassing, not to make them private from outside callers. Subclasses can now safely define their own Thingy.__frob()
and it'll be kept separate from the parent class.
As such, you can manually apply the same transformation in the test:
Thingy(...)._Thingy__frob(-2)
E.g. add _ClassName
to the start of the method name.
Just to be explicit; the feature is primarily meant to avoid name clashes between attributes used by subclasses. It just also happens to work for method names, as methods are essentially attributes too.
Upvotes: 5