I\'m wondering if Python has anything like the C# anonymous classes feature. To clarify, here\'s a sample C# snippet:
var foo = new { x = 1, y = 2 };
var bar
If you want the instance to be anonymous as well (using the object directly in an expression), then you're bound to use the type-expression. However in many cases the instance will not be anonymous, but assigned to a variable. This case can be handled in a reasonable way in python by using metaclasses or decorators.
An example using decorator:
def anonymous(cls):
return cls()
@anonymous
class foo:
x = 42
def bar(self):
return self.x
The decorator in this case causes the class foo
to be instantiated an put into the variable foo
instead of the class itself. The class itself will not be accessible from any namespace although it has a name:
>>> foo
<__main__.foo instance at 0x7fd2938d8320>
>>> foo.bar()
42
Another feature in python that accomodates for many use cases is that it's legal to define classes locally, which means that they would become a symbol local to that function, which in turns gives it some degree of anonymity.
As show above, I get a good intellisense from pycharm for this and I love this solution...
>>> def anonymous(cls):
... return cls()
>>> class fooo:
... @anonymous
... class c:
... D=10
>>> fooo.c.D
10
Looks like Python 3.3 has added exactly this thing in the form of types.SimpleNamespace class.
Quoted from this page:
class Struct:
def __init__(self, **entries): self.__dict__.update(entries)
def __eq__(self, other): return self.__dict__ == other.__dict__
def __ne__(self, other): return self.__dict__ != other.__dict__
options = Struct(answer=42, linelen = 80, font='courier')
options.answer
>>> 42
options.answer = 'plastics'
vars(options)
>>> {'answer': 'plastics', 'font': 'courier', 'linelen': 80}
I don't remember offhand if there's a built-in but writing it yourself is shorter than typing your question. :-)
class record(object):
def __init__(self, **kwargs): self.__dict__ = kwargs
def __eq__(self, r2): return self.__dict__ == r2.__dict__
def __ne__(self, r2): return self.__dict__ != r2.__dict__
foo = record(x=1, y=2)
bar = record(y=2, x=1)
foo == bar # => true
The type(...) form will fail the structural comparison requirement (without getting really ugly). The dict(...) form doesn't meet the attribute accessor requirement.
The attrdict seems to fall in the middle somewhere:
class attrdict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
a = attrdict(x=1, y=2)
b = attrdict(y=2, x=1)
print a.x, a.y
print b.x, b.y
print a == b
But it means defining a special class.
OK, I just noticed the update to the question. I'll just note that you can specify dict
for the bases parameter and only need to specify the constructor then (in the icky type expression). I prefer attrdict. :-)