2

Sometimes I use classes without any structure, i.e.

class Foo(object):
    pass

foo = Foo()

I wonder if there is a more compact way which avoids the clumsy, meaningless definition. Can one directly initialize blank object-instances?

2 Answers 2

4

Use type():

>>> foo = type('Foo', (), {})()
>>> foo
<__main__.Foo object at 0x100499f50>
Sign up to request clarification or add additional context in comments.

Comments

3
foo = object()

is the common way.

4 Comments

I was sure as death to have checked that, but obviously I haven't. Thanks!
Note that you won't be able to add any attributes to object instances, like foo in this example. If you just need a unique object (for instance, as a sentinel value), this is a good way to go, but if you need to be able to store data in the object it won't work.
foo1=object() and foo2=Foo() behave different, even though the Foo class got no additional ingredients. Is there a deeper reason for this strange behavior? Is object really a class or something spooky nonstandard?
@flonk object is a built-in class.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.