PEP 8 is the style guide for Python code. Following PEP 8 guidelines helps ensure consistency and readability in Python codebases.
Naming Conventions:
snake_case
.CamelCase
.UPPERCASE_WITH_UNDERSCORES
.Indentation:
Line Length:
Blank Lines:
Imports:
from module import *
).Whitespace:
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
List comprehensions and generator expressions are brief ways to create lists and iterators. They enhance readability and can be more efficient than traditional loops.
[expression for item in iterable if condition]
Example:
# Traditional loop
squares = []
for x in range(10):
squares.append(x**2)
# List comprehension
squares = [x**2 for x in range(10)]
(expression for item in iterable if condition)
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)
@property
Decorator for Attribute Access ControlThe @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.
@property
to define a getter method.@<property_name>.setter
to define a setter method.@<property_name>.deleter
to define a deleter method.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