Thanks for responding, Jason!
I'll investigate your idea of using a metaclass.
I actually have the same need as the one exemplified with a class, in
the original post, but also for some code run _when the module is
imported_, and I don't see how metaclasses could be used, in this case
(maybe I'm too naive, here :) ).
Here is an example of why I need tests that use variables that would
be temporary if there were no tests: I redefine functions of the math
module, where some of these functions are given analytical derivatives
_through the temporary variable_, which contain the analytical
formulas (the temporary variable in itself is not needed anymore by
the module, when the corresponding math functions are redefined). I
want to make sure that the analytical derivatives yield the same
result as numerical approximate derivatives. If I delete the
temporary variable when they are not needed anymore (tests
notwithstanding), the test function does not have access to the list
of functions to be checked. If I don't delete the temporary
dictionary of analytical formulas, then the module has a useless
attribute.
In the particular case above, I could certainly make the temporary
variables private, even though this would still leave an unnecessary
memory footprint. But in the case of a class (like in the example I
gave initially), non-deleted temporary variables appear as attributes
of each instance, which is confusing to any user doing a dir() on
instances. To respond to your question: I could test the behavior of
instances, but the testing code would be less robust, as it would have
to duplicate the list of attributes of interest, instead of using the
list of attributes currently defined in a variable (that I wish could
be temporary). Thus, if I later decide to modify the class to be
tested, I need not to forget to update the testing code as well (by
extending a list of defined attributes in _both_ the class and the
testing code). I wanted to use a variable in order to avoid just
that: the class construction and the test would perform the attribute
construction and the test on the same elements (defined in the
temporary list)--this would be possible if there was a way of running
the test during class construction.
So far, the best solution I see is to use private (__) temporary
variables for modules (the memory footprint of these variables is
small), and to duplicate the lists used during class construction in
the tests for the class (even though this violation of the "don't
duplicate" rule makes me cringe :) ).
I hope that the example of why I asked the initial question is
clearer!
All the best,
EOL