Python Anonymous Object [Complete Guide with Code Examples] - JSON Viewer

Python Anonymous Object [Complete Guide with Code Examples]


Python is a widely used general-purpose, high-level, interpreted programming language for a variety of applications, including data analysis, artificial intelligence, web development, and many others.

Several tools and constructs offered by Python make it possible for programmers to create understandable and efficient code. Anonymous objects, usually referred to as anonymous classes or anonymous instances, are one such feature.

In this article, we’ll define anonymous objects, explain how to make them, and give some usage examples.

What are Anonymous Objects in Python?

An anonymous object in Python is a class instance that is created without a name. It is also referred to as an anonymous instance or class. It is created on the fly and used to hold data temporarily. Anonymous objects are created using the object constructor, which is a built-in class in Python.

Python Anonymous Object Creation:

With Python, making anonymous objects is simple. We use the class statement to declare a class before creating an instance of that class without giving it a name in order to create an anonymous object. The following syntax is used to create anonymous objects:

class MyClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y
obj = MyClass(1, 2)
anonymous_obj = type('', (), {'x': 1, 'y': 2})()

We build the class MyClass in the code sample above, and it has the two instance variables x and y. Then, we make a new instance of that class and give it to the obj variable. We also create an anonymous object with the same values for x and y using the type constructor.

The first argument to the type constructor is the name of the class, which is empty in this case since we don’t want to give the class a name.

As we don’t want the class to inherit from any other classes, the second argument, a tuple of base classes, is empty in this case. A dictionary that associates the names of the instance variables with their values is the third argument.

Let’s examine a few straightforward instances to demonstrate how to build anonymous objects in Python:

Example 1: Making a single-attribute anonymous object

obj = type('', (), {'x': 5})()
print(obj.x) # Output: 5

As an illustration, let’s make an anonymous object with a single attribute named ‘x’ and a value of 5. Then, using dot notation, we print the value of the ‘x’ attribute.

Example 2: Making a multi-attribute anonymous object

obj = type('', (), {'x': 5, 'y': 10, 'z': 15})()
print(obj.x) # Output: 5
print(obj.y) # Output: 10
print(obj.z) # Output: 15

In this illustration, we create an anonymous object with the three attributes “x,” “y,” and “z,” each having the values 5, 10, and 15. The values of each characteristic are then printed using dot notation.

Example 3: Using a method to create an anonymous object

obj = type('', (), {'add': lambda x, y: x + y})()
print(obj.add(6, 2)) # Output: 8

This example creates an anonymous object with a single method called “add” that accepts two arguments and returns the total of those arguments. We next use parameters 6 and 2 to invoke the anonymous object’s “add” method, printing the outcome.

Example 4: Creating an anonymous object with a dictionary attribute

obj = type('', (), {'data': {'x': 2, 'y': 3, 'z': 4}})()
print(['x']) # Output: 2
print(['y']) # Output: 3
print(['z']) # Output: 4

In this example, a dictionary with three keys and values is created as a single anonymous object with the attribute name “data”. The values of each key are then printed using dictionary notation.

Example 5: Creating an anonymous object with a list attribute

obj = type('', (), {'numbers': [1, 2, 3, 4, 5]})()
print(obj.numbers[2]) # Output: 3

In this instance, we make an anonymous object with a single attribute named “numbers” that contains a list of integers. The value located at index 2 of the list is then printed using list notation.

Example 6: Creating an anonymous object with a tuple attribute

obj = type('', (), {'coordinates': (10, 20)})()
print(obj.coordinates[1]) # Output: 20

In this demonstration, we make an anonymous object with a single attribute called “coordinates” that is a tuple of two integers. The second value of the tuple is then printed using tuple notation.

Why are anonymous objects used in Python? What’s the benefit of that?

An object that is formed in Python without a class declaration or a name is referred to as an anonymous object. It is typically made on the spot and only utilised briefly. Because they make it possible to rapidly and simply build objects with little code, anonymous objects can be helpful.

Anonymous objects have the benefit of allowing attributes to be assigned to them dynamically without the need to specify a class or named instance of a class. Your code becomes more adaptable and simple to change as a result.

Another benefit is that anonymous objects can be used to encapsulate intricate data structures or to abstract away implementation details. By doing this, your code will be simpler to read and comprehend, which will be helpful when working with huge or complex data sets.

Also, the ability to create test fixtures or mock objects that replicate a certain object or behaviour without requiring a full implementation makes anonymous objects helpful for testing.

Ultimately, anonymous objects can be a useful tool in your Python programming toolbox because they make it simple and quick to build things. Yet, it’s crucial to use them in a way that preserves the simplicity and readability of the code.


To sum up, Python’s anonymous objects feature might be helpful for quickly constructing objects without the requirement for a class definition or a name. They enable testing, dynamic attribute assignment, abstraction, and succinct syntax.

But, it’s crucial to utilise anonymous objects sparingly and in a way that keeps the code straightforward and readable.

Anonymous objects, like any programming tools, have advantages and disadvantages, and it is up to the programmer to choose whether they are the best option for a given issue.