I have wondered the same thing. I enjoy the convenience of x.foo
instead of x["foo"]
; a single period is far easier to type (and get correct) than all of [""]
.
The advantage of a dict is that anything can be a key. (Well, anything hashable.) But when I have a bunch of values I want to just bundle together, the key names I pick are valid identifiers anyway.
Here's the basic version of this idea:
class struct(object):
pass
x = struct()
x.foo = 1
As long as you are going to this much trouble, you might as well add the __init__()
that handles kwargs
for convenient initialization. But I'm lazy and I was hoping for something built-in.
I tried this, which doesn't work:
x = object()
x.foo = 1 # raises AttributeError exception
I asked about it, and the answer I got was that object
is the root of all types in Python; it is as small as possible. If it could act like a class instance, with its own __dict__
attribute, then every object ever created in Python would need an attached __dict__
.
I would have liked to see struct
added as a built-in for Python 3.x. But I understand why it was not: keeping the language small and clean is a worthy goal, and this feature is trivially easy to code up yourself.