python - Are object literals Pythonic? -
javascript has object literals, e.g.
var p = { name: "john smith", age: 23 }
and .net has anonymous types, e.g.
var p = new { name = "john smith", age = 23}; // c#
something similar can emulated in python (ab)using named arguments:
class literal(object): def __init__(self, **kwargs): (k,v) in kwargs.iteritems(): self.__setattr__(k, v) def __repr__(self): return 'literal(%s)' % ', '.join('%s = %r' % in sorted(self.__dict__.iteritems())) def __str__(self): return repr(self)
usage:
p = literal(name = "john smith", age = 23) print p # prints: literal(age = 23, name = 'john smith') print p.name # prints: john smith
but kind of code considered pythonic?
have considered using named tuple?
using dict notation
>>> collections import namedtuple >>> l = namedtuple('literal', 'name age')(**{'name': 'john smith', 'age': 23})
or keyword arguments
>>> l = namedtuple('literal', 'name age')(name='john smith', age=23) >>> l literal(name='john smith', age=23) >>> l.name 'john smith' >>> l.age 23
it possible wrap behaviour function enough
def literal(**kw): return namedtuple('literal', kw)(**kw)
the lambda equivalent be
literal = lambda **kw: namedtuple('literal', kw)(**kw)
but think it's silly giving names "anonymous" functions
Comments
Post a Comment