Why do only callable objects get a __name__?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Nov 18 18:37:03 EST 2013
On Mon, 18 Nov 2013 13:02:26 -0800, John Ladasky wrote:
> I am implementing a state machine. The outputs of the various states in
> the machine have variable contents. I started by making dictionaries
> for each state output, but I soon tired of the bracket-and-quote-mark
> syntax for referring to the contents of these state output dictionaries.
> That's why I am switching to named tuples. It doesn't affect the
> __name__ issue, since dictionaries also cannot be called.
>
> I want to capture the names of the executed states in a record of the
> state machine's history. This information is already encoded in the
> namedtuple's type.
I find this rather confusing. Does every state have it's own unique
namedtuple class?
state1 = namedtuple("State1", ("x", "y"))(1, 2)
state2 = namedtuple("State2", ("x", "y"))(5, 7)
state3 = namedtuple("State3", ("x", "y"))(0, 2)
[...]
Seems excessive -- you're defining many classes, each one of which has
only a single instance. I'd be more inclined to just use a class object
directly, with a little helper function to handle the tedious bits:
def state(name, x, y):
class Inner(object):
pass
Inner.x = x
Inner.y = y
Inner.__name__ = Inner.name = name
return Inner
And in use:
py> state1 = state('state1', 100, 101)
py> state1
<class '__main__.state1'>
py> state1.name
'state1'
py> state1.x
100
But I don't really understand how you are using these state objects, so
I'm not sure if this is appropriate or not.
--
Steven
More information about the Python-list
mailing list