/
🐍

Python Paradigm

https://docs.python.org/3/howto/functional.html
python
On this page

Programming Paradigm in Python

A programming paradigm is a fundamental style or approach to writing code. It encompasses a set of principles, concepts, and methodologies that guide how a programmer designs, organizes, and implements code.

Different paradigms emphasize distinct aspects of programming, such as data organization, control flow, and modularity. Each paradigm has its own key features that define its scope and application.

Key features of programming paradigms

Each paradigm has many key features.

  • Data Structure: How data is organized, stored, and manipulated.
  • Control Flow: How instructions are executed and decisions are made.
  • Modularity: How code is organized into reusable and maintainable modules.
  • Abstraction: The level of detail and complexity exposed to the programmer.
  • Inheritance and Composition: How code can be reused and extended.

Imperative (Procedural) Programming

Imperative programming or Procedural programming is one of the most intuitive paradigms, focusing on describing the step-by-step sequence of instructions required to achieve a specific goal. It revolves around changing program state through statements that modify variables and data structures.

In Python, imperative programming is evident in the straightforward sequence of statements that update variables, perform calculations, and control flow. The paradigm’s simplicity makes it an ideal choice for tasks where control over individual instructions is critical.

python
numbers = [1, 2, 3, 4, 5]
result = 0
for number in numbers:
result += number
print(result)

Declarative Programming

Declarative programming focuses on specifying what should be done rather than how it should be done. It promotes a more abstract and high-level approach to problem-solving.

In Python, list comprehensionsa and generator expressions exemplify declarative programming. This paradigm leads to more concise and readable code by abstracting away implementation details.

python
numbers = [1, 2, 3, 4, 5]
even_numbers = [n for n in numbers if n % 2 == 0]
print(even_numbers)

Functional Programming

Functional programming treats computation as the evaluation of mathematical functions and avoids changing state and mutable data. It emphasizes immutable data and the use of pure functions that produce consistent outputs for the same inputs.

Python supports functional programming through features like lambda functions, higher-order functions, and tools like map, filter, and reduce.

python
def square(number):
return number ** 2
numbers = [1, 2, 3, 4, 5]
squares = list(map(square, numbers))
print(squares)

Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) revolves around the concept of objects, which encapsulate both data (attributes) and behavior (methods) related to a specific entity. This paradigm emphasizes code modularity, reusability, and the modeling of real-world entities as classes.

Python renowned for its support of OOP, allowing developers to create classes, define inheritance hierarchies, and achieve polymorphism through method overriding and interfaces.

python
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start_engine():
print(f"the {self.brand} {self.model}'s engine is running...")
my_car = Car("Toyota", "Yaris")
my_car.start_engine()

Parallel Programming

Python offers powerful libraries like asyncio and threading for concurrent programming and multiprocessing for parallel execution.

The asyncio library facilitates asynchronous programming, enabling tasks to run concurrently without blocking the main program. This is especially useful for I/O-bound tasks such as network requests.

python
import asyncio
async def fetch_data() -> dict:
await asyncio.sleep(2)
return {'data': 'fetched'}
if __name__ == '__main__':
result = asyncio.run(fetch_data())
print(result)

Metaprogramming

Python’s dynamic and introspective features enable powerful metaprogramming techniques. Metaprogramming involves writing code that manipulates or generates other code. Decorators and Metaclass, for instance, are a form of metaprogramming in Python.

They allow you to modify the behavior of functions or classes without changing their source code. This advanced paradigm empowers developers to create reusable and flexible code structures.

python
# Metaclass
class OnlyOneBases(type):
def __new__(cls, clsname, bases, clsdict):
if len(bases) > 1:
raise TypeError("Inherited multiple base classes!!!")
return super().__new__(cls, clsname, bases, clsdict)
class Base(metaclass=OnlyOneBases):
pass
# no error is raised
class A(Base):
pass
# no error is raised
class B(Base):
pass
# This will raise an error!
class C(A, B):
pass
# Decorators
def make_pretty(func):
def inner():
print("I got decorated")
func()
return inner
@make_pretty
def ordinary():
print("I am ordinary")
ordinary()
Want to make your own site like this?
Try gatsby-theme-code-notes by Zander Martineau.
Life of Code