getting the state of an object

Chris Rebert clp2 at rebertia.com
Sun Oct 7 06:18:21 EDT 2012


On Sun, Oct 7, 2012 at 1:50 AM, Franck Ditter <franck at ditter.org> wrote:
> Hi !
>
> Another question. When writing a class, I have often to
> destructure the state of an object as in :
>
> def foo(self) :
>     (a,b,c,d) = (self.a,self.b,self.c,self.d)
>     ... big code with a,b,c,d ...

I would generally strongly frown on doing that (at least if the
destructuring is actually that trivial). The "self."s are only 5
characters; that's hardly burdensome or verbose. Just write it out
each time, i.e.:
def foo(self):
    … code with self.a, self.b, self.c, self.d ...

Or in the extreme case, use "s" instead of "self" (using the name
"self" is just a convention; it's not a language keyword or anything).

> So I use the following method :
>
> def state(self) :
>     return (self.a,self.b,self.c,self.d)
>
> so as to write :
>
> def foo(self) :
>     (a,b,c,d) = self.state()
>     ... big code with a,b,c,d ...
>
> This is probably not the best Python way to code, is it ?

Indeed it isn't. Don't bother with the pointless destructuring.
And/or refactor your method so it's less big.

> Is there a simple way to get the *ordered* list of instance
> variables as given in the parameter list of __init__ ?

There is no guaranteed correspondence whatsoever between __init__()'s
parameters and the resulting object's instance variables. At a
minimum, such a hack would fail to account for instance variables that
are merely derived from the parameters (e.g. self.length =
len(some_list_param) ) or are initialized to constant values (e.g.
self.cache = {} ). And then there's private instance variables (e.g.
self._foo = foo_param ); if the parameter is named "_foo", you're
doing it wrong.

That said, you can obtain the names of the parameters using the
`inspect` module in the std lib.

> __dict__ gives it but not in order…

You can actually "fix" that, not that I at all recommend doing so:
http://docs.python.org/dev/reference/datamodel.html#preparing-the-class-namespace

Cheers,
Chris



More information about the Python-list mailing list