Created
April 23, 2020 14:06
-
-
Save victorusachev/b774a48384fe6a0d83cbc662750245d9 to your computer and use it in GitHub Desktop.
Declarative description of environment variables for environs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from typing import Any, Callable, Dict, Optional, Type, TypeVar | |
| from environs import Env | |
| __all__ = ('EnvVar',) | |
| T = TypeVar('T') | |
| class EnvVar: | |
| name: Any | |
| def __init__( | |
| self, | |
| method: Callable[[Env, str, Optional[Dict[str, Any]]], Any] = Env.str, | |
| name: Optional[str] = None, | |
| kwargs: Optional[Dict[str, Any]] = None, | |
| ): | |
| self.name = name | |
| self.method = method | |
| self.kwargs = kwargs or {} | |
| def __set_name__(self, owner: Type[T], name: str) -> None: | |
| if not self.name: | |
| self._check_name(owner, name) | |
| self.name = name | |
| def __get__(self, instance: T, owner: Type[T]) -> Any: | |
| if not instance: | |
| raise AttributeError( | |
| f"type object '{owner.__name__}' " | |
| f"has no attribute '{self.name}'" | |
| ) | |
| return self.method(instance, self.name, **self.kwargs) | |
| def __set__(self, instance, value): | |
| raise TypeError("can't set attribute") | |
| @staticmethod | |
| def _check_name(owner, name): | |
| if not name.isupper(): | |
| raise RuntimeError( | |
| f'{owner.__qualname__}.{name} must be in uppercase' | |
| ) | |
| class Environment(Env): | |
| PATH = EnvVar() | |
| if __name__ == '__main__': | |
| env = Environment() | |
| print(env.PATH) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment