Nick Coghlan wrote:
By assigning to __dict__ directly, you can use the attribute view either as it's own dictionary (by not supplying one, or supplying a new one), or as a convenient way to programmatically modify an existing one. For example, you could use it to easily bind globals without needing the 'global' keyword:

Py> class attr_view(object):
...     def __init__(self, data):
...         self.__dict__ = data
...
Py> def f():
...   gbls = attr_view(globals())
...   gbls.x = 5
...
Py> x
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'x' is not defined
Py> f()
Py> x
5

Hmm... interesting. This isn't the main intended use of Bunch/Struct/whatever, but it does seem like a useful thing to have... I wonder if it would be worth having, say, a staticmethod of Bunch that produced such a view, e.g.:


class Bunch(object):
    ...
    @staticmethod
    def view(data):
        result = Bunch()
        result.__dict__ = data
        return result

Then you could write your code as something like:

gbls = Bunch.view(globals())

I'm probably gonna need more feedback though from people though to know if this is a commonly desired use case...

Steve
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to