Skip to content

Anonymous Class in Python

Anonymous Class in Python : Create classes without a name

Section titled “Anonymous Class in Python : Create classes without a name”

In Python, an anonymous class is a class without a name. Anonymous classes are also known as Lambda classes. They are used to create classes on the fly without defining a class name.

Anonymous classes are created using the type function. The type function takes three arguments: the class name, a tuple of base classes, and a dictionary of class attributes.

Syntax:

Syntax
type(class_name, base_classes, class_attributes)

Here,

  • class_name: The name of the class. If you want to create an anonymous class, you can pass an empty string "".
  • base_classes: A tuple of base classes. If the class has no base class, you can pass an empty tuple ().
  • class_attributes: A dictionary of class attributes. You can define the class variables and methods in this dictionary.
  • The type function returns a class object.
  • You can create an instance of the anonymous class by calling the class object.

Here is an example of an anonymous class in Python:

anonymous_class.py
# Create an instance of the anonymous class
obj = type("AnonymousClass", (MyClass,), {"name": "Alice"})()
 
# Call the display method of the anonymous class
obj.display()

In the above example, we have created an anonymous class AnonymousClass that inherits from the MyClass class. The anonymous class has a class attribute name with the value "Alice". We have created an instance of the anonymous class and called the display method.

When we run the above code, it will output:

Command
C:\Users\username\Desktop> python anonymous_class.py
Hello, Alice!
  1. Dynamic Class Creation: Anonymous classes allow you to create classes dynamically at runtime.
  2. Simplifies Code: Anonymous classes help in simplifying the code by creating classes without a name.
  3. Encapsulation: Anonymous classes encapsulate the class definition within a single expression.
  4. Code Reusability: Anonymous classes can be reused at multiple places in the code.
  5. Flexibility: Anonymous classes provide flexibility in creating classes with different attributes and methods.
  6. Functional Programming: Anonymous classes are used in functional programming to create classes on the fly.
  7. Reduced Boilerplate Code: Anonymous classes reduce the boilerplate code required to define a class.
  8. Cleaner Code: Anonymous classes help in writing cleaner and concise code.
  9. Less Code: Anonymous classes require less code to define a class compared to
  1. Readability: Anonymous classes can make the code less readable if used excessively.
  2. Debugging: Debugging anonymous classes can be difficult as they do not have a name.
  3. Testing: Testing anonymous classes can be challenging as they are not named.
  4. Documentation: Anonymous classes lack proper documentation as they do not have a name.
  5. Complexity: Anonymous classes can introduce complexity in the code if not used judiciously.

Variables and Methods in Anonymous Classes

Section titled “Variables and Methods in Anonymous Classes”

You can define class variables and methods in anonymous classes using the dictionary of class attributes. Here is an example:

anonymous_class.py
# Create an instance of the anonymous class
obj = type("AnonymousClass", (), {"name": "Alice", "display": lambda self: print(f"Hello, {self.name}!")})()
 
# Call the display method of the anonymous class
obj.display()

In the above example, we have defined a class variable name and a class method display in the dictionary of class attributes. We have created an instance of the anonymous class and called the display method.

When we run the above code, it will output:

Command
C:\Users\username\Desktop> python anonymous_class.py
Hello, Alice!

In Python, anonymous classes are used to create classes without a name. Anonymous classes are created using the type function. They are useful for creating classes dynamically at runtime. Anonymous classes help in simplifying the code and encapsulating the class definition within a single expression. However, excessive use of anonymous classes can make the code less readable and difficult to debug. It is recommended to use anonymous classes judiciously to maintain code readability and simplicity. For more information, you can refer to the official documentation. For more tutorials, you can visit the Python Central Hub.


diagram a class statement is a call to type() mermaid
Defining a class is not special syntax with private machinery -- it evaluates the body into a namespace and calls type(name, bases, namespace). Doing that call yourself produces an identical class, which is what lets a library build classes from data at runtime. Python has no anonymous class; the nearest tools are lambda, SimpleNamespace and type().
sketch Building a class at runtime, and the three near-substitutes p5.js
type() with three arguments creates a class identical to one written with a class statement -- same isinstance behaviour, same __bases__, same everything. Beside it are the tools people reach for when they want something lighter: a lambda for a one-expression function, and SimpleNamespace for attribute access with no class at all.
pch.quizTag pch.quizDefaultTitle
  1. What does `type('Dyn', (object,), {'x': 1})` produce?

    pch.quizShowAnswer

    C — A class, identical to one made with a `class` statement — Verified: `isinstance(Dyn(), Dyn)` is True and `__bases__` is `(object,)`. A `class` statement evaluates its body into a namespace and makes exactly this call.

  2. Does Python have anonymous classes?

    pch.quizShowAnswer

    B — No — `lambda` gives an anonymous function; a class always gets a name — `type()` still takes a name as its first argument. The nearest lightweight substitutes are `lambda` for a one-expression function and `SimpleNamespace` for attribute access with no class.

  3. When is building a class with `type()` justified?

    pch.quizShowAnswer

    B — When the class must be built from data available only at runtime — a schema, a header row — ORMs and serialisation libraries do this. Otherwise write the class: a dynamic one has no source to read, no line for a traceback to point at, and nothing an editor can jump to.

  4. What is `types.SimpleNamespace` good for?

    pch.quizShowAnswer

    B — Attribute-style access to a handful of values without defining a class — `SimpleNamespace(a=1, b=2)` gives `ns.a` without a class definition, and it has a readable `repr`. For a record with behaviour or fixed fields, a dataclass or NamedTuple is better.

Try it: Anonymous / Dynamic Class Exercises

Section titled “Try it: Anonymous / Dynamic Class Exercises”

Exercise 2 – type() to Create a Dynamic Class

Section titled “Exercise 2 – type() to Create a Dynamic Class”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading