decorators.py: Demonstrates Python decorators, including:- Simple decorator with logging
- Chaining decorators
- Class-based decorator
- Use of functools.wraps
file_context_manager.py: Shows how to create a custom context manager class for file resource management using__enter__and__exit__.network_context_manager.py: Demonstrates context manager usage for network connections with@contextmanagerfromcontextlib, and exception suppression withcontextlib.suppress.generators_iterators.py: Demonstrates Python generators, iterators, generator expressions, memory efficiency,yield from, and theitertoolsmodule.lock_context_manager_example.py: Demonstrates proper lock acquisition and release using context managers (threading.Lock).login_required_example.py: Demonstrates a simple@login_requireddecorator for access control.
To run the decorators example:
python decorators.pyTo run the generators and iterators example:
python generators_iterators.pyTo run the file context manager example:
python file_context_manager.pyTo run the network context manager example:
python network_context_manager.pyTo run the lock context manager example:
python lock_context_manager_example.pyTo run the login required decorator example:
python login_required_example.pySample output:
[LOG] Calling function: ...
[LOG] ...
Result: ...
(Shows logs for function calls, decorator chaining, class-based decorators, and @wraps effect.)
Sample output:
Countdown:
5 4 3 2 1 0
Squares:
0 1 4 9 16
Double Countdown:
3 2 1 0 1 2 3
Large range sum (1M): 499999500000
--- itertools examples ---
itertools.count:
10 11 12 13 14 15
itertools.cycle:
A B A B A B
itertools.permutations:
(1, 2) (1, 3) (2, 1) (2, 3) (3, 1) (3, 2)
itertools.combinations:
(1, 2) (1, 3) (2, 3)
Sample output:
[ManagedFile] Opened example.txt
[ManagedFile] Closed example.txt
[ManagedFile] Opened example.txt
[file_management_example] File content: Hello, context managers!
[ManagedFile] Closed example.txt
Sample output (if no server is running):
[managed_socket] Connection failed: [Errno 111] Connection refused
[network_connection_example] No connection established.
[managed_socket] Socket closed
[suppress_example] FileNotFoundError suppressed.
If a server is running on localhost:5001, you will see a successful connection and data sent message.
Sample output:
Manual lock management:
[manual_lock_example] Trying to acquire lock...
[manual_lock_example] Lock acquired. Doing work...
[manual_lock_example] Lock released.
With-statement lock management:
[with_lock_example] Trying to acquire lock...
[with_lock_example] Lock acquired. Doing work...
[with_lock_example] Lock released (automatically by context manager).
Sample output:
--- Not authenticated ---
Access denied: user not authenticated.
--- Authenticated ---
User 'bob' is authenticated. Access granted.
Welcome to bob's profile!