encapsulation checking features

Alex Martelli aleax at aleax.it
Mon Apr 14 17:57:08 EDT 2003


<posted & mailed>

Eric Scharff wrote:

> I love python's semantics for rapid prototyping, but I was wondering if
> there was a way to turn on warnings so that for other kinds of code, I
> can avoid certain common uglinesses. :)

PyChecker is the popular "lint-like" tool for Python.  However, I
very much doubt it can possibly warn about the specific usages that
you worry about, as they're quite common and idiomatic in Python.

Perhaps you can build some kludges to help, depending on exactly
what you're after.

> Specifically, is there a "lint-like" tool to:
> 
>  * warn if instance variables are created outside of a constructor?
> 
>   class K:
>     def __init__(self):
>       self.a = 6  #okay
>     def example(self):
>       self.b = 66 # not as good
> 
>   myVar = K()
>   myVar.c = 666  # really bad

To catch assignments you need a __setattr__.  In turn, it has to
know when __init__ has finished executing, so it can then warn
for assignments it wouldn't warn about otherwise.  To avoid having
to ensure your __init__ does explicit marking of its termination,
you're probably better off designing a custom metaclass that
overrides type.__call__ and does the "marking" that "initialization
is now finished" (and it may as well insert the __setattr__ too).


>  * warn if instance variables are used outside of instance methods
>    (encouraging the use of getters and setters)

That's even harder, because knowing if you ARE "inside an instance
method" or outside it is really tough.

But I really don't see the problem here.  If you want myVar.x to
call an accessor, you make x into a property of myVar's class,
period.  Absolutely no need to design trivial do-nothing accessors
either -- you can perfectly well have all client code access all
instance variables you want, and if and then such "variables"
need to be "computed on the fly" or have special effects when
set, then you make them into properties, hey presto.

> These are great features to have, but it'd be nice to have warnings to
> discourage their use at times.

I can see that for the "ensure all instance variables exist at
the end of __init__".  I can't see that, given the existence of
properties, for "no access to instance attributes from outside
of methods".  Perhaps you can clarify what advantage the latter
would provide, that properties just can't...?


Alex






More information about the Python-list mailing list