Master Advanced Python Structures: Comprehensions, Generators, Decorators & More
This guide explores advanced Python design structures—including list comprehensions, generator expressions, zip processing, decorators, context managers, descriptors, metaclasses, and common patterns—explaining their syntax, best‑practice usage, memory implications, and providing clear code examples for each concept.
Content This article presents several advanced Python design structures and how to use them. Depending on requirements such as fast lookup, data consistency, or indexing, you can choose appropriate data structures or combine them to build logical, easy‑to‑understand data models. Comprehensions List comprehensions combine a for‑loop, optional if‑condition, and an expression into a single line, allowing mapping or filtering of a list. An input sequence A variable representing each element An optional predicate expression An output expression that transforms selected elements Example: generate squares of positive numbers. <code>num = [1, 4, -5, 10, -7, 2, 3, -1] filtered_and_squared = [] for number in num: if number > 0: filtered_and_squared.append(number ** 2) print(filtered_and_squared) # [1, 16, 100, 4, 9] </code> Using filter , lambda and map simplifies the code: <code>filtered_and_squared = list(map(lambda x: x**2, filter(lambda x: x>0, num))) print(filtered_and_squared) # [1, 16, 100, 4, 9] </code> The most concise form is a list comprehension: <code>filtered_and_squared = [x**2 for x in num if x>0] print(filtered_and_squared) # [1, 16, 100, 4, 9] </code> Iterate over each element x in num Predicate checks x > 0 Output expression squares the element List comprehensions build the entire list in memory, which may be problematic for very large data sets. Generators solve this by yielding items lazily. Generator Expressions Generator expressions use parentheses instead of brackets: <code>filtered_and_squared = (x**2 for x in num if x>0) for item in filtered_and_squared: print(item) # 1 16 100 4 9 </code> They reduce memory usage and can be wrapped in a function: <code>def square_generator(threshold): return (x**2 for x in num if x>threshold) print(square_generator(0)) # <generator object ...> for k in square_generator(0): print(k) </code> zip() Function Process multiple sequences in parallel: <code>alist = ['a1', 'a2', 'a3'] blist = ['1', '2', '3'] for a, b in zip(alist, blist): print(a, b) # a1 1 # a2 2 # a3 3 </code> Decorators Decorators wrap a function or class to add functionality, similar to Aspect‑Oriented Programming. They are defined as functions that return a wrapper. <code>import time from functools import wraps def timethis(func): @wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(func.__name__, end - start) return result return wrapper @timethis def countdown(n): while n > 0: n -= 1 countdown(100000) # ('countdown', 0.007) </code> Decorators can also be implemented as classes by defining __call__ : <code>class decorator(object): def __init__(self, f): print('inside decorator.__init__()') f() def __call__(self): print('inside decorator.__call__()') @decorator def function(): print('inside function()') function() # inside decorator.__init__() # inside function() # Finished decorating function() # inside decorator.__call__() </code> Context Management (contextlib) Define a class with __enter__ and __exit__ to use with the with statement: <code>class demo: def __init__(self, label): self.label = label def __enter__(self): self.start = time.time() def __exit__(self, exc_ty, exc_val, exc_tb): end = time.time() print(f'{self.label}: {end - self.start}') with demo('counting'): n = 10000000 while n > 0: n -= 1 # counting: 1.36 </code> Using @contextmanager simplifies the pattern: <code>from contextlib import contextmanager import time @contextmanager def demo(label): start = time.time() try: yield finally: end = time.time() print(f'{label}: {end - start}') with demo('counting'): n = 10000000 while n > 0: n -= 1 # counting: 1.32 </code> Descriptors Descriptors control attribute access by defining __get__ , __set__ , or __delete__ methods. <code>class Celsius(object): def __init__(self, value=0.0): self.value = float(value) def __get__(self, instance, owner): return self.value def __set__(self, instance, value): self.value = float(value) class Temperature(object): celsius = Celsius() temp = Temperature() print(temp.celsius) # 0.0 </code> Lazy loading example using a descriptor: <code>import weakref class lazyattribute(object): def __init__(self, f): self.data = weakref.WeakKeyDictionary() self.f = f def __get__(self, obj, cls): if obj not in self.data: self.data[obj] = self.f(obj) return self.data[obj] class Foo(object): @lazyattribute def bar(self): print('Being lazy') return 42 f = Foo() print(f.bar) # Being lazy \n 42 print(f.bar) # 42 </code> Metaclasses Metaclasses are "classes of classes" and control class creation. <code>class demo(object): pass obj = demo() print('Class of obj is', obj.__class__) # <class '__main__.demo'> print('Class of demo is', demo.__class__) # <type 'type'> </code> Patterns Python follows the "Easier to Ask Forgiveness than Permission" (EAFP) principle, encouraging try‑except blocks for robust code. Common patterns include Singleton, Null Object, Observer, and Constructor shortcuts. Summary Thank you for reading. Feel free to leave comments or questions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
