Skip to content

Commit

Permalink
clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
Joaopeuko committed Apr 27, 2024
1 parent ec89d58 commit e91afb6
Show file tree
Hide file tree
Showing 7 changed files with 32 additions and 18 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ repos:
rev: v1.9.0
hooks:
- id: mypy
args: ['--ignore-missing-imports', '--strict']
args: ['--strict']

- repo: https://github.com/pre-commit/mirrors-prettier
rev: v4.0.0-alpha.8
Expand Down
4 changes: 2 additions & 2 deletions examples/examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
message = "🔒 <Data Secured> 🔒"
secured = Secured('examples/config-secrets.yaml', secure=True, message=message)

print(secured.config_secrets.name)
print(secured.config_secrets["name"])
print(secured.config_secrets.name) # type: ignore
print(secured.config_secrets["name"]) # type: ignore

ad = AttrDict(secure=True, message=message)
ad['password'] = 'my_secret'
Expand Down
10 changes: 5 additions & 5 deletions secured/attribute.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# A type variable that can be any type.
T = TypeVar('T')

class AttrDict(dict):
class AttrDict(dict): # type: ignore
"""
A dictionary subclass that allows attribute-style access and can optionally secure its leaf values.
Expand All @@ -23,7 +23,7 @@ class AttrDict(dict):
'<Custom Secured>'
"""

def __init__(self, *args, secure: bool = False, message: str = "<Sensitive data secured>", **kwargs) -> None:
def __init__(self, *args, secure: bool = False, message: str = "<Sensitive data secured>", **kwargs) -> None: # type: ignore
"""
Initialize the AttrDict with the same arguments as a normal dict, plus options to secure.
Expand All @@ -43,7 +43,7 @@ def _convert_dicts(self) -> None:
for key, value in list(self.items()):
self[key] = self._convert_value(value)

def _convert_value(self, value: Any) -> T | Secure:
def _convert_value(self, value: dict | str) -> 'AttrDict' | Secure | str: # type: ignore
"""
Converts and possibly secures the value based on its type and the secure setting.
Expand All @@ -59,7 +59,7 @@ def _convert_value(self, value: Any) -> T | Secure:
return Secure(value, self.message)
return value

def __getattr__(self, item: str) -> T | Secure:
def __getattr__(self, item: str) -> 'AttrDict' | Secure:
"""
Enables attribute-style access to dictionary keys.
Expand All @@ -73,7 +73,7 @@ def __getattr__(self, item: str) -> T | Secure:
AttributeError: If the attribute does not exist.
"""
if item in self:
return self[item]
return self[item] # type: ignore
else:
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{item}'")

Expand Down
18 changes: 16 additions & 2 deletions secured/log_manager.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
import logging

def setup_default_logger():
def setup_default_logger() -> logging.Logger:
"""
Setup a default logger with basic configuration.
Sets up and returns a logger with a basic configuration.
This function configures a logger to output log messages to the console (standard output).
It sets the logger's level to INFO, meaning it will handle INFO and higher level messages (WARNING, ERROR, CRITICAL).
The log output format includes the time of the log entry, the logger's name, the log level, and the log message.
If a logger with handlers is already set up for the module, this function does not add another handler.
Returns:
logging.Logger: A logger instance configured with a console handler.
Example:
>>> logger = setup_default_logger()
>>> logger.info("This is an info message")
2023-01-01 12:00:00 - __main__ - INFO - This is an info message
"""
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
Expand Down
2 changes: 1 addition & 1 deletion secured/secure.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class Secure(str):
'<Data Hidden>'
"""

def __new__(cls, original: str, message: str = "<Sensitive data secured>"):
def __new__(cls, original: str, message: str = "<Sensitive data secured>"): # type: ignore
"""
Create a new Secure instance that appears as a custom message.
Expand Down
6 changes: 3 additions & 3 deletions secured/secured.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import os
import yaml
import yaml # type: ignore
from typing import List

from .log_manager import setup_default_logger
Expand All @@ -8,7 +8,7 @@
from .attribute import AttrDict

class Secured:
def __init__(self, yaml_paths: str | List[str] = None, secure: bool = False,
def __init__(self, yaml_paths: str | List[str] = None, secure: bool = False, # type: ignore
as_attrdict: bool = True, message: str = "<Sensitive data secured>", logger=None):
"""
Initialize a Secured object to manage YAML configuration securely.
Expand Down Expand Up @@ -54,7 +54,7 @@ def load_yaml(self, yaml_paths: str | List[str], secure: bool) -> None:
self.logger.error(f"Error parsing YAML file {path}: {e}")
continue

def create_config(self, data: dict, secure: bool) -> AttrDict | dict[str, Secure]:
def create_config(self, data: dict[str, dict], secure: bool) -> AttrDict | dict[str, Secure]:
"""
Create a configuration from data loaded from a YAML file.
Expand Down
8 changes: 4 additions & 4 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import tomlkit
from setuptools import setup, find_packages
import tomlkit # type: ignore
from setuptools import setup, find_packages # type: ignore

# Read and parse the pyproject.toml file
with open("pyproject.toml", "r") as toml_file:
pyproject = tomlkit.parse(toml_file.read())

def convert_version(poetry_version):
def convert_version(poetry_version): # type: ignore
""" Convert Poetry version specifier to setuptools specifier. """
if poetry_version.startswith('^'):
version = poetry_version[1:]
Expand All @@ -16,7 +16,7 @@ def convert_version(poetry_version):

# Extract dependencies and convert versions
dependencies = [
f"{pkg}{convert_version(ver)}" for pkg, ver in pyproject['tool']['poetry']['dependencies'].items()
f"{pkg}{convert_version(ver)}" for pkg, ver in pyproject['tool']['poetry']['dependencies'].items() # type: ignore
if pkg != "python"
]

Expand Down

0 comments on commit e91afb6

Please sign in to comment.