Unlock Python’s Power: 10 Advanced Features Every Developer Should Master
This article explores ten advanced Python features—including context managers, metaclasses, coroutines, abstract base classes, descriptors, threading, duck typing, data classes, list comprehensions, and custom iterators—explaining their purpose, core syntax, and practical code examples to help developers write cleaner, more efficient code.
1. Context Managers
Context managers manage resources such as files or database connections, ensuring proper cleanup after use. They are implemented with the with statement.
<code>with open("file.txt", "w") as file:
file.write("Hello, World!")</code>2. Metaclasses
Metaclasses control class creation and behavior; they are “classes of classes” that determine how classes behave.
<code>class Meta(type):
def __new__(cls, name, bases, dct):
print(f"Creating class {name}")
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass</code>Metaclasses can automatically generate or modify class attributes and methods, avoiding repetitive code. For example, they can add a __str__ method to every class:
<code>class AutoStrMeta(type):
def __new__(cls, name, bases, dct):
dct['__str__'] = lambda self: f"{self.__class__.__name__} instance"
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=AutoStrMeta):
pass
obj = MyClass()
print(obj) # Output: MyClass instance</code>Metaclasses can also implement the singleton pattern, ensuring a class has only one instance.
<code>class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Singleton(metaclass=SingletonMeta):
pass
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True</code>Use metaclasses carefully, as overuse can make code complex and hard to maintain.
3. Coroutines
Coroutines use the async and await keywords to achieve asynchronous programming, allowing execution to be paused and resumed.
<code>import asyncio
async def async_task():
print("Task started")
await asyncio.sleep(1)
print("Task completed")
asyncio.run(async_task())</code>4. Abstract Base Classes (ABCs)
ABCs define a blueprint for other classes, ensuring derived classes implement specific methods. They are provided by the abc module.
<code>from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Woof!"
dog = Dog()
print(dog.sound())</code>ABCs cannot be instantiated and require subclasses to implement all abstract methods.
5. Descriptors
Descriptors manage attribute access, providing fine‑grained control over getting, setting, and deleting values.
<code>class Descriptor:
def __get__(self, instance, owner):
return instance._value
def __set__(self, instance, value):
instance._value = value * 2
class MyClass:
attribute = Descriptor()
obj = MyClass()
obj.attribute = 10
print(obj.attribute) # 20</code>6. Multithreading and Multiprocessing
These mechanisms enable parallel execution and support concurrent tasks.
<code>import threading
def task():
print("Task executed")
thread = threading.Thread(target=task)
thread.start()
thread.join()</code>7. Duck Typing and Polymorphism
Python emphasizes “duck typing”: an object’s suitability is determined by the methods it supports rather than its explicit type.
<code>class Bird:
def fly(self):
print("Flying")
class Airplane:
def fly(self):
print("Flying with engines")
def test_fly(obj):
obj.fly()
test_fly(Bird())
test_fly(Airplane())
</code>Duck typing allows objects with compatible behavior to be used interchangeably without inheritance.
8. Data Classes
Since Python 3.7, the @dataclass decorator simplifies creation of classes that primarily store data by automatically generating __init__ , __repr__ , __eq__ , and other methods.
<code>from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(10, 20)
print(p) # Point(x=10, y=20)
</code>Data classes are ideal for simple data containers, reducing boilerplate and improving readability.
9. List Comprehensions
List comprehensions support nesting and conditional logic.
<code>matrix = [[j for j in range(3)] for i in range(3)]
print(matrix)
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares)
</code>10. Custom Iterators
Custom iterators let you control how an object is iterated.
<code>class MyIterator:
def __init__(self, max):
self.max = max
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current < self.max:
self.current += 1
return self.current
else:
raise StopIteration
iterator = MyIterator(5)
for value in iterator:
print(value)
</code>Code Mala Tang
Read source code together, write articles together, and enjoy spicy hot pot together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.