Registry example
This commit is contained in:
73
generics_2_registry_class.py
Normal file
73
generics_2_registry_class.py
Normal file
@ -0,0 +1,73 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, Generic, TypeVar
|
||||
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class Registry(Generic[T]):
|
||||
def __init__(self) -> None:
|
||||
self._store: Dict[str, T] = {}
|
||||
|
||||
def set_item(self, key: str, value: T) -> None:
|
||||
self._store[key] = value
|
||||
|
||||
def get_item(self, key: str) -> T:
|
||||
return self._store[key]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Database:
|
||||
host: str
|
||||
port: int
|
||||
user: str
|
||||
password: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class ApiEndpoint:
|
||||
url: str
|
||||
method: str
|
||||
|
||||
|
||||
def main():
|
||||
database_registry = Registry[Database]()
|
||||
database_registry.set_item(
|
||||
"cloud",
|
||||
Database(
|
||||
host="localhost",
|
||||
port=5432,
|
||||
user="pero",
|
||||
password="pero001",
|
||||
),
|
||||
)
|
||||
database_registry.set_item(
|
||||
"central",
|
||||
Database(
|
||||
host="central.someserver.com",
|
||||
port=5432,
|
||||
user="mirko",
|
||||
password="mirko001",
|
||||
),
|
||||
)
|
||||
|
||||
db = database_registry.get_item("cloud")
|
||||
print(db)
|
||||
|
||||
api_endpoints_registy = Registry[ApiEndpoint]()
|
||||
api_endpoints_registy.set_item(
|
||||
"get user", ApiEndpoint(url="/user/{user_id}", method="GET")
|
||||
)
|
||||
api_endpoints_registy.set_item(
|
||||
"create user", ApiEndpoint(url="/user", method="POST")
|
||||
)
|
||||
api_endpoints_registy.set_item(
|
||||
"update user", ApiEndpoint(url="/user/{user_id}", method="PUT")
|
||||
)
|
||||
|
||||
api_endpoint = api_endpoints_registy.get_item("create user")
|
||||
print(api_endpoint)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1,25 +0,0 @@
|
||||
from typing import Dict, Generic, TypeVar
|
||||
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class Registry(Generic[T]):
|
||||
def __init__(self) -> None:
|
||||
self._store: Dict[str, T] = {}
|
||||
|
||||
def set_item(self, key: str, value: T) -> None:
|
||||
self._store[key] = value
|
||||
|
||||
def get_item(self, key: str) -> T:
|
||||
return self._store[key]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
family_name_reg = Registry[str]()
|
||||
family_age_reg = Registry[int]()
|
||||
|
||||
family_name_reg.set_item("husband", "steve")
|
||||
family_name_reg.set_item("dad", "john")
|
||||
|
||||
family_age_reg.set_item("steve", 30)
|
||||
Reference in New Issue
Block a user