Python Fundamentals & Language Mechanics: An Engineering Teardown
This technical note provides a comprehensive architectural teardown of core Python mechanics, derived from the implementations in the standalone repository python-fundamentals.
1. Object Model & Dynamic Typing Mechanics
In Python, everything is an object. Every variable reference is a pointer to a heap-allocated PyObject structure containing:
ob_refcnt: Reference count for automatic memory management via Garbage Collection.ob_type: Pointer to the object's type object (e.g.,PyTypeObjectforint,str,list).
Variable 'x' (Name in local scope table) ----> Pointer ----> [ PyObject: refcnt=1, type=int, value=42 ]
Dynamic Typing & Mutable vs Immutable Types
Python variables are untyped labels bound to strongly-typed objects. Primitive types (int, float, str, tuple, bool) are immutable — modifying them creates a new object instance in memory. Collections (list, dict, set) are mutable and allow in-place modification.
2. Control Flow, Iteration & Mathematical Algorithms
Python control flow extends standard conditional branching with unique iteration constructs like the loop else clause, which executes only if the loop completes without encountering a break statement.
Strong Numbers Algorithmic Proof
A Strong Number is defined as a positive integer where the sum of the factorials of its individual digits equals the original number.
For example, for :
import math
def is_strong_number(n: int) -> bool:
"""Verifies whether n is a Strong Number in O(k) digit time complexity."""
digits = [int(d) for d in str(n)]
return sum(math.factorial(d) for d in digits) == n
3. Data Structures & Computational Complexity
| Data Structure | Implementation | Access / Lookup Time | Insertion / Deletion Time | Common Operations |
|:---|:---|:---|:---|:---|
| List | Dynamic Array (PyListObject) | by index | amortized at end | Append, Slice, In-place sort |
| Tuple | Fixed-size Immutable Array | by index | Immutable (N/A) | Unpacking, Hashable Keys |
| Set | Hash Table (Keys only) | average | average | Union (), Intersection (), Difference () |
| Dictionary | Open Addressing Hash Table | average | average | Key-value pairs, Frequency counting |
Extraction of Second Largest Element in Time
Sorting an array to find the maximum elements requires time. The linear single-pass scanning algorithm extracts the second maximum in time and auxiliary space:
def find_second_largest(numbers: list[int]) -> int | None:
if len(numbers) < 2:
return None
first = second = float('-inf')
for num in numbers:
if num > first:
second = first
first = num
elif num > second and num != first:
second = num
return second if second != float('-inf') else None
4. Object-Oriented Design & Dunder Protocols
Python implements OOP paradigms through explicit self reference passing, operator overloading via Dunder (Double Underscore) methods, and encapsulation.
Encapsulation, Properties & Dunder Protocols
from abc import ABC, abstractmethod
class BaseShape(ABC):
"""Abstract Base Class enforcing geometric interface contracts."""
@abstractmethod
def area(self) -> float:
pass
class Circle(BaseShape):
def __init__(self, radius: float) -> None:
self.__radius = max(0.0, radius) # Private attribute via name mangling
@property
def radius(self) -> float:
return self.__radius
def area(self) -> float:
return 3.1415926535 * (self.__radius ** 2)
def __str__(self) -> str:
return f"Circle(radius={self.__radius:.2f}, area={self.area():.2f})"
5. Decorator Mechanics & Higher-Order Functions
Decorators leverage Python's first-class functions and closure scopes to wrap function execution dynamically without mutating source code.
import functools
import time
from typing import Callable, Any
def execution_logger(func: Callable[..., Any]) -> Callable[..., Any]:
"""Higher-order decorator measuring execution latency and logging arguments."""
@functools.wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
start_time = time.perf_counter()
result = func(*args, **kwargs)
elapsed = (time.perf_counter() - start_time) * 1000
print(f"[LOG] {func.__name__} executed in {elapsed:.3f}ms")
return result
return wrapper
@execution_logger
def compute_factorial_sum(n: int) -> int:
return sum(math.factorial(i) for i in range(1, n + 1))
- 🔗 GitHub Repository: github.com/nischalneupanee/python-fundamentals
- 📖 Next Study Notes: [[python/all-about-numpy-array-computing]], [[python/pandas-data-analysis-mastery]], and [[python/data-visualization-matplotlib]]