getting the state of an object

Oscar Benjamin oscar.j.benjamin at gmail.com
Sun Oct 7 06:28:09 EDT 2012


On Oct 7, 2012 9:57 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 ...
>

What's wrong with the above? It seems fine to me. Alternatively, don't
bother: just use self.a etc.

> 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 just seems needlessly confusing. Someone reading your code will have
to see that line, find the state function, check the order of the return
values and then confirm that it matches up with the order in the original
line. The first version doesn't have this problem. You can see that it's
correct just by looking at it.

> This is probably not the best Python way to code, is it ?
> Is there a simple way to get the *ordered* list of instance
> variables as given in the parameter list of __init__ ?

I don't know about simple but you can get the names of the arguments from
the __init__ method object using the inspect module. Then you can use
getattr te recover the attribute values.

I wouldn't bother though. Explicit is better than implicit. If you want to
extract the instance attributes as local variables then just write the one
line that does it as in your first example.

Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121007/ad1cf10b/attachment.html>


More information about the Python-list mailing list