This post originated from an RSS feed registered with Python Buzz
by Ben Last.
Original Post: A Useful Pot to Keep Things In
Feed Title: The Law Of Unintended Consequences
Feed URL: http://benlast.livejournal.com/data/rss
Feed Description: The Law Of Unintended Consequences
Snippet time, with appropriate thanks to Pooh Bear. I liked this ASPN Python recipe that initializes an object from the parameters to __init__, but thought it was a bit all-encompassing (not to mention a bit too clever with sys._getFrame). I happened to be in need of something similar for Zope development - a way to return a collection of associated data from an External Method, so I knocked this up:
class Bag(object):
def __init__(self, **kw):
"""Initialise, and set attributes from all keyword arguments."""
#This is a bit of Zope magic to allow access from ZPT code.
self.__allow_access_to_unprotected_subobjects__=1
#Set an attribute for every keyword argument.
for k in kw.keys():
setattr(self,k,kw[k])
I can create and initialize it all in one go, and use it as a sort of struct equivalent.
See, Zope allows you to pass dicts back from Python to ZPT and access the elements with the usual ZPT "/" based syntax; so if I have a dict:
{ 'id' : 'eric', 'title' : 'Eric the Object' }
I can access it from ZPT with stuff like
<p tal:content="thedict/id">goes here</p><br>
<b tal:content="thedict/title">and the title goes here</b>
which gives me
eric
Eric the Object
But if I need to invoke Python, then I need to remember that the dict is accessed via ['id'] (etc). ZPT hides that distinction, which means that it's easy to forget. Using a Bag to keep the data in means that the notations are consistent - "/" in ZPT, "." in Python.
Now I shall go and work out a reason for putting a BurstBalloon in one...