Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way of creating an object with arbitrary attributes in Python?

Tags:

python

Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be).

One solution would be to create a new class that has the attributes the code expects, but as I call other code that also needs objects with (other) attributes, I'd have to create more and more classes.

A shorter solution is to create a generic class, and then set the attributes on instances of it (for those who thought of using an instance of object instead of creating a new class, that won't work since object instances don't allow new attributes).

The last, shortest solution I came up with was to create a class with a constructor that takes keyword arguments, just like the dict constructor, and then sets them as attributes:

class data:     def __init__(self, **kw):         for name in kw:             setattr(self, name, kw[name])  options = data(do_good_stuff=True, do_bad_stuff=False) 

But I can't help feeling like I've missed something obvious... Isn't there a built-in way to do this (preferably supported in Python 2.5)?

like image 481
Blixt Avatar asked Feb 17 '10 11:02

Blixt


People also ask

How do you create an attribute of an object in Python?

Python provides a function setattr() that can easily set the new attribute of an object. This function can even replace the value of the attribute. It is a function with the help of which we can assign the value of attributes of the object.

What are object attributes in Python?

An instance/object attribute is a variable that belongs to one (and only one) object. Every instance of a class points to its own attributes variables. These attributes are defined within the __init__ constructor.

Where and how are instance attributes created in Python?

An instance attribute is a Python variable belonging to one, and only one, object. This variable is only accessible in the scope of this object and it is defined inside the constructor function, __init__(self,..) of the class.


1 Answers

type('', (), {})() will create an object that can have arbitrary attributes.

Example:

obj = type('', (), {})() obj.hello = "hello" obj.world = "world" print obj.hello, obj.world   # will print "hello world" 

type() with three arguments creates a new type.

  • The first argument '' is the name of the new type. We don't care about the name, so we leave it empty.

  • The second argument () is a tuple of base types. Here object is implicit.

  • The third argument is a dictionary of attributes of the new object. We start off with no attributes so it's empty {}.

In the end we instantiate a new instance of this new type with ().

like image 154
data Avatar answered Sep 28 '22 04:09

data