Python gettattr and setattr again because I can’t just leave it alone

In this post:

https://looselyconnected.wordpress.com/2012/04/05/python-getattr-and-setattr/

I was playing around with blurring the distinction between getters and setters in Python objects. tarcisiocrocomo gave me this tip for the win:

class Foo(object):
I was able to get the same results with this:

__getitem__ = object.__getattribute__
__setitem__ = object.__setattr__

Are there any meaningful differences?

Victory! So here’s the little Ob class I wrote and I throw it around where I want attributes and items… usually in unit tests, although when I’m good I use flexmock.

class Ob(object):
    __getitem__ = object.__getattribute__
    __setitem__ = object.__setattr__

    def __init__(self, **kwargs):
        # see if the passed in initialization values
        if kwargs:
            for key in kwargs.keys():
                self[key] = kwargs[key]

Now I just need to get it to pretty print… hm….

from pprint import pprint
ob = Ob()
ob.name = 'hello!'
pprint(ob)
....hrm
Advertisements

Leave a comment

Filed under opinionizing, python, utility

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s