Best Pythonic Approach to Annotation/Metadata?

Chris Rebert clp2 at rebertia.com
Fri Jul 16 05:22:56 EDT 2010


On Thu, Jul 15, 2010 at 12:37 PM, Sparky <samnsparky at gmail.com> wrote:
> Hello Python community!
>
> I am building a JSON-RPC web application that uses quite a few models.
> I would like to return JSON encoded object information and I need a
> system to indicate which properties should be returned when the object
> is translated to a JSON encoded string. Unfortunately, this
> application runs on top of Google's App Engine and, thus, private
> attributes are not an option. Also, a preliminary search leads me to
> believe that there are no real established ways to annotate variables.
> Ideally I want to do something like:
>
> def to_JSON(self):
>        returnDict = {}
>        for member in filter(someMethod, inspect.getmembers(self)):
>                returnDict[member[0]] = member[1]
>        return json.dumps(returnDict)
>
> I recognize that two solutions would be to 1) include a prefix like
> "public_" before variable names or 2) have a list/tuple of attributes
> that should be transmitted, simply using the "in" operator. However,
> both these options seem like a pretty ungraceful way to do it. Does
> anyone else have an idea? Are there any established methods to apply
> metadata / annotations to variables in Python or do you believe one of
> the above is a good "pythonic" way to solve this problem?

Those are about as Pythonic as you're going to get; I for one find the
prefix (or similar) solution rather neat (Good luck pulling it off in
a less dynamic language!), but option (2) is probably better in your
particular case.
Remember that at class-definition-time, Python has no idea what
instance variables an object will have, so nothing exists for you to
annotate; hence we're left with solutions of the forms you've given.
You /could/ do something involving decorators and property()s, but
that would be more verbose, more unnecessarily complicated, and less
Pythonic.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list