How to Create Inline Objects With Properties? [Python One-Liner]

Problem: How to create a Python object in a single line of code? And how can you associate custom properties to this object in the same line?

Example: Say, you want to do something like this pseudocode snippet:

var newObject = new({'property' : 'value' }) # returns 'value'

However, you cannot do the same in Python because this would create a dictionary:

new_object = {'property': 'value'}
# raises an AttributeError

This raises an AttributeError because there’s no attribute property associated to the dictionary object. To access the dictionary key in this case, you must use the syntax new_object['property'].

So, how to create an inline Python object with attributes in a single line of Python code?

Here’s a quick overview of our three methods:

Exercise: Do all three methods produce the same output? Run the code to test it!

Let’s dive into each of those methods in greater detail!

Method 1: Use Python’s built-in type() function

The type(name, bases, dict) function creates and returns a new object. It takes three arguments that allow you to customize the object:

  • name: this is the class name of the new object. It becomes the name attribute, so that you can use to access the argument value.
  • bases: this is a tuple of one or more tuple values that defines the base classes. You can access the content via the object.bases attribute of the newly-created object.
  • dict: this is the namespace with class attributes and methods definitions. You can create custom attributes and methods here. In case, you want to access the values later, you can use the object.__dict__ attribute on the newly-created object.

Here’s how you can use the type() function to build a new object with attributes in a single line of code:

obj = type('obj', (object,), {'property': 'value'})

Let’s see how we can access the attribute property of the newly-created object:

>>> obj
<class '__main__.obj'>

It works! The created class has an associated attribute property that is set to the 'value'.

However, this is not an instance (or object), yet. It’s only a class definition. To actually create an instance, you must use the following method with a trailing pair of parentheses.

obj = type('obj', (object,), {'property': 'value'})()

Now, you can create an arbitrary number of instances.

Method 2: Lambda Function Without Return Value + Dynamic Attributes

The second method is less clean—it’s more a hack—but it work beautifully! The idea is to create an anonymous function using the lambda keyword and associate the desired attributes right afterwards:

>>> obj = lambda: None
>>> = 'value'

You can also one-linerize this by using the semicolon:

obj = lambda: None; = 'value'

This achieves the desired result and uses only a single line of Python code!

Method 3: Use Named Tuples From Collections Module

You can also use named tuples from the collections module.

from collections import namedtuple

obj = namedtuple('obj', ['property'])('value')

The resulting output is the property value 'value'.

  • The first part of the expression namedtuple('obj', ['property']) enables you to create new object using the obj(...) constructor.
  • The second part of the expression associates the string 'value' to the tuple attribute 'property'.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!