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 of Anonymous Classes
Section titled “Syntax of Anonymous Classes”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
typefunction 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:
# 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:
C:\Users\username\Desktop> python anonymous_class.py
Hello, Alice!Advantages of Anonymous Classes
Section titled “Advantages of Anonymous Classes”- Dynamic Class Creation: Anonymous classes allow you to create classes dynamically at runtime.
- Simplifies Code: Anonymous classes help in simplifying the code by creating classes without a name.
- Encapsulation: Anonymous classes encapsulate the class definition within a single expression.
- Code Reusability: Anonymous classes can be reused at multiple places in the code.
- Flexibility: Anonymous classes provide flexibility in creating classes with different attributes and methods.
- Functional Programming: Anonymous classes are used in functional programming to create classes on the fly.
- Reduced Boilerplate Code: Anonymous classes reduce the boilerplate code required to define a class.
- Cleaner Code: Anonymous classes help in writing cleaner and concise code.
- Less Code: Anonymous classes require less code to define a class compared to
Limitations of Anonymous Classes
Section titled “Limitations of Anonymous Classes”- Readability: Anonymous classes can make the code less readable if used excessively.
- Debugging: Debugging anonymous classes can be difficult as they do not have a name.
- Testing: Testing anonymous classes can be challenging as they are not named.
- Documentation: Anonymous classes lack proper documentation as they do not have a name.
- 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:
# 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:
C:\Users\username\Desktop> python anonymous_class.py
Hello, Alice!Conclusion
Section titled “Conclusion”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.
flowchart TD
A["class C(Base): x = 1"] --> B["evaluate the body into a dict"]
B --> C["type('C', (Base,), {'x': 1})"]
C --> D["a class object bound to the name C"]
E["calling type() yourself"] --> D
F["there is no anonymous CLASS"] --> G["lambda -- an anonymous FUNCTION"]
F --> H["SimpleNamespace -- attributes without a class"]
F --> I["type(...) -- a class with a name you supply"]
Check yourself
Section titled “Check yourself”-
What does `type('Dyn', (object,), {'x': 1})` produce?
Verified: `isinstance(Dyn(), Dyn)` is True and `__bases__` is `(object,)`. A `class` statement evaluates its body into a namespace and makes exactly this call.
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.
-
Does Python have anonymous classes?
`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.
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.
-
When is building a class with `type()` justified?
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.
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.
-
What is `types.SimpleNamespace` good for?
`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.
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 1 – Lambda as Callable Object
Section titled “Exercise 1 – Lambda as Callable Object”Exercise 2 – type() to Create a Dynamic Class
Section titled “Exercise 2 – type() to Create a Dynamic Class”Exercise 3 – Unnamed Nested Callable
Section titled “Exercise 3 – Unnamed Nested Callable”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading