Why does python not have a mechanism for data hiding?

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Jun 4 07:19:16 CEST 2008


On Wed, 04 Jun 2008 13:50:42 +1000, Ben Finney wrote:

> alex23 <wuwei23 at gmail.com> writes:
> 
>> So the basic answers I'm seeing that "do just fine" are:
>> 
>> 1. Don't test private functions.
>> 2. Add functionality _to_ the private functions for testing.
>> 3. Change the interface for the purpose of testing.
>> 
>> All of which seem exceptionally inefficient and run counter to the
>> whole purpose of unit testing.
> 
> It seems you have a different idea of what unit testing is for from
> me.

For me it's about finding bugs where documentation and implementation
disagree.  And if you document private functions it makes sense to me to
also test if they work as documented.  Because the official API relies on
the correct implementation of the private parts it uses under the hood.

> Isn't the entire point of encapsulation to separate internal
> components from the external interface?
> 
> Why would a unit test, the whole purpose of which is to assert some
> aspect of the external behaviour of the unit of code, care about how
> that code unit is implemented internally?

One part of writing unit tests is invoking functions with arguments that
you think are "corner cases".  For example test if a function that takes a
list doesn't bomb out when you feed the empty list into it.  Or if it
handles all errors correctly.

If a function `f()` calls internally `_g()` and that function might even
call other private functions, then you have to know how `f()` works
internally to create input that checks if error handling in `_g()` works
correctly.  So it goes against your understanding of unit tests.

What do you do in such a situation?  Build something from untested private
parts and just test the assembled piece?  I prefer to test the private
functions too.  After all the private functions are not private to the
everybody, there *are* functions that rely on them working correctly.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list