-
Notifications
You must be signed in to change notification settings - Fork 0
Representing FPP Scala in Python
In Python, use abstract base classes
- Abstract base classes can not be instantiated
- Can define both concrete/default implementations and abstract methods
- Abstract methods must be implemented in the concrete subclass that inherits from the abstract base class
- Supports multiple inheritance - Python classes can be derived from one or more abstract base classes
- See Abstract Base Class docs for more information https://docs.python.org/3/library/abc.html
In Python, use the Singleton pattern
- Creates an instance only if there is no instance created so far, otherwise return the instance that has already been created
In Python, use the dataclass module with frozen=True for immutability (attributes can not be changed after the object has been initialized).
- Creates boilerplate code and is typically used for data-holding objects.
- Module includes decorators and functions for generating special methods like
__init__(used to initialize attributes).
- Module includes decorators and functions for generating special methods like
- See docs for more information https://docs.python.org/3/library/dataclasses.html
In Python, use the TypeVar type variable (part of the typing library) to define generic functions.
Example:
from typing import TypeVar, Sequence
T = TypeVar('T')
# generic function
def some_generic_func(l: List[T]) -> T:
passCan also define generic classes extending the typing.Generic class.
Example:
from typing import TypeVar, Generic
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
# Create an empty list with items of type T
self.items: list[T] = []
def push(self, item: T) -> None:
self.items.append(item)https://docs.python.org/3/library/typing.html#typing.TypeVar
Use python's typing.Optional when using type hints.
typing.Optional[T] can be used to indicate that a variable
or function parameter might be None or a value of type T
Python does not have private variables, but a convention exists when naming a variable to mark it as private. Prefix a variable with an underscore to denote that it should be treated as a non-public part of the class.
Class variables are essentially Python's implementation of static variables.
- Attributes that belong to the class and are not tied to a specific instance of the class
Using module as a namespace is the most pythonic way to represent static members
class Circle(val radius: Double) {
def area: Double = Circle.pi * radius * radius
}
object Circle {
// Static-like member
val pi: Double = 3.14159
// Static-like method
def fromDiameter(diameter: Double): Circle = new Circle(diameter / 2)
}# circle.py
pi = 3.14159
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return pi * self.radius ** 2
def from_diameter(diameter):
return Circle(diameter / 2)