How to create inline objects with properties?

Question:

In Javascript it would be:

var newObject = { 'propertyName' : 'propertyValue' };
newObject.propertyName;  // returns "propertyValue"

But the same syntax in Python would create a dictionary, and that’s not what I want

new_object = {'propertyName': 'propertyValue'}
new_object.propertyName  # raises an AttributeError
Asked By: Jader Dias

||

Answers:

I don’t know if there’s a built-in way to do it, but you can always define a class like this:

class InlineClass(object):
    def __init__(self, dict):
        self.__dict__ = dict

obj = InlineClass({'propertyName' : 'propertyValue'})
Answered By: Smashery

I like Smashery’s idea, but Python seems content to let you modify classes on your own:

>>> class Inline(object):
...     pass
...
>>> obj = Inline()
>>> obj.test = 1
>>> obj.test
1
>>>

Works just fine in Python 2.5 for me. Note that you do have to do this to a class derived from object – it won’t work if you change the line to obj = object.

Answered By: Chris Lutz
obj = type('obj', (object,), {'propertyName' : 'propertyValue'})

there are two kinds of type function uses.

Answered By: SilentGhost

Peter’s answer

obj = lambda: None
obj.propertyName = 'propertyValue'
Answered By: Jader Dias
class test:
    def __setattr__(self,key,value):
        return value


myObj = test()
myObj.mykey = 'abc' # set your property and value
Answered By: user149513

It is easy in Python to declare a class with an __init__() function that can set up the instance for you, with optional arguments. If you don’t specify the arguments you get a blank instance, and if you specify some or all of the arguments you initialize the instance.

I explained it here (my highest-rated answer to date) so I won’t retype the explanation. But, if you have questions, ask and I’ll answer.

If you just want a generic object whose class doesn’t really matter, you can do this:

class Generic(object):
    pass

x = Generic()
x.foo = 1
x.bar = 2
x.baz = 3

An obvious extension would be to add an __str__() function that prints something useful.

This trick is nice sometimes when you want a more-convenient dictionary. I find it easier to type x.foo than x["foo"].

Answered By: steveha

Python 3.3 added the SimpleNamespace class for that exact purpose:

>>> from types import SimpleNamespace

>>> obj = SimpleNamespace(propertyName='propertyValue')
>>> obj
namespace(propertyName='propertyValue')

>>> obj.propertyName
'propertyValue'

In addition to the appropriate constructor to build the object, SimpleNamespace defines __repr__ and __eq__ (documented in 3.4) to behave as expected.

Answered By: Sylvain Leroux

Another viable option is to use namedtuple:

from collections import namedtuple

message = namedtuple('Message', ['propertyName'], verbose=True)
messages = [
    message('propertyValueOne'),
    message('propertyValueTwo')
]
Answered By: b.b3rn4rd

SilentGhost had a good answer, but his code actually creates a new object of metaclass type, in other words it creates a class. And classes are objects in Python!

obj = type('obj', (object,), {'propertyName' : 'propertyValue'})
type(obj) 

gives

<class 'type'>

To create a new object of a custom or build-in class with dict attributes (aka properties) in one line I’d suggest to just call it:

new_object = type('Foo', (object,), {'name': 'new object'})()

and now

type(new_object) 

is

<class '__main__.Foo'>

which means it’s an object of class Foo

I hope it helps those who are new to Python.

Answered By: Leo Skhrnkv