Skip to main content

Posts

Showing posts with the label Python functions

Advanced Guide to Python Decorators | Expert Python Techniques

In Python, decorators are a powerful feature used to modify or enhance functions and classes. They are a key part of advanced metaprogramming and are frequently used in logging, authentication, caching, metrics, and tracing in production systems. This document provides an in-depth explanation of the syntax and all common use cases of Python decorators with professional examples aimed at deep learning engineers. 1. Basic Syntax of a Decorator def my_decorator(func): def wrapper(*args, **kwargs): print("Before function call") result = func(*args, **kwargs) print("After function call") return result return wrapper @my_decorator def say_hello(name): print(f"Hello, {name}!") say_hello("Alice") @my_decorator is equivalent to writing say_hello = my_decorator(say_hello) . 2. Stacking Multiple Decorators def deco1(func): def wrapper(*args, **kwargs): print("deco1") ...

Python 'global' and 'nonlocal' Keywords Explained with Examples

In Python, the keywords global and nonlocal are used when dealing with variable scope . In other words, they help determine where a variable is located when you access or modify it. 1. Scope Refresher Before we jump in, remember that  scope  refers to the part of a program where a variable is accessible. Local scope : Inside a function Global scope : Outside all functions Enclosing scope : A function inside another function Here's a visual diagram to help you understand variable scopes: 2.The  global  Keyword The global keyword is used to  modify a variable outside of the current function , specifically the one in the global scope. Normally, assigning to a variable inside a function creates a local variable. If you want to change a variable that exists at the global(module) level, you need to declare it global. Example 1: x = 10 def change_global () : global x x = 20 change_global() print(x) # Output: 20 Example 2: counter = 0 ...