Code-Memo

Pythonic Code

Writing Idiomatic Python Code (PEP 8 Guidelines)

PEP 8 is the style guide for Python code. Following PEP 8 guidelines helps ensure consistency and readability in Python codebases.

Example adhering to PEP 8:

class MyClass:
    def __init__(self, name, value):
        self.name = name
        self.value = value

    def display(self):
        print(f"Name: {self.name}, Value: {self.value}")

def my_function(param1, param2):
    return param1 + param2

Using List Comprehensions and Generator Expressions

List comprehensions and generator expressions are brief ways to create lists and iterators. They enhance readability and can be more efficient than traditional loops.

Example:

# Traditional loop
squares = []
for x in range(10):
    squares.append(x**2)

# List comprehension
squares = [x**2 for x in range(10)]

Example:

# List comprehension
squares = [x**2 for x in range(10)]

# Generator expression
squares_gen = (x**2 for x in range(10))

# Convert generator to list
squares = list(squares_gen)

Leveraging Python’s @property Decorator for Attribute Access Control

The @property decorator in Python allows you to define methods that behave like attributes, providing controlled access to instance variables. This is useful for encapsulation and validation.

Example:

class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        if not value:
            raise ValueError("Name cannot be empty")
        self._name = value

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        if value < 0:
            raise ValueError("Age cannot be negative")
        self._age = value

    @age.deleter
    def age(self):
        del self._age

# Usage:
person = Person("Alice", 30)
print(person.name)  # Output: Alice
person.age = 35
print(person.age)   # Output: 35
del person.age

Benefits of Pythonic Code