Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recursive assignment of fields in settings.py to the app.settings object #78

Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion pyttman/core/internals.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
import json
from collections import UserDict


import pyttman
from pyttman.core.containers import MessageMixin, Reply
Expand Down Expand Up @@ -32,6 +35,12 @@ def depr_graceful(message: str, version: str):
out = f"{message} - This was deprecated in version {version}."
warnings.warn(out, DeprecationWarning)

class CustomUserDict(UserDict):

# constructor
def __init__(self, dictionary):
self.data = dictionary
self.__dict__.update(dictionary)
Copy link
Collaborator

@dotchetter dotchetter Sep 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this class is redundant, since we already have the Settings class which could implement this API instead.. I'd prefer if the Settings class would handle a recursive assignment of self for all sub-dictionaries, instead of the first level being a Settings object and all subnodes being of a different type, for no apparent reason.


class Settings:
"""
Expand Down Expand Up @@ -60,10 +69,20 @@ def __init__(self, **kwargs):
self.LOG_FORMAT: str | None = None
self.LOG_TO_STDOUT: bool = False

[setattr(self, k, v) for k, v in kwargs.items()
[self.__set_attr(k, v) for k, v in kwargs.items()
if not inspect.ismodule(v)
and not inspect.isfunction(v)]

def __set_attr(self, k, v):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to PEP-8, single _ hint to a private method - unless mangling is required, but it' highly unlikely to be needed here.

tmp = v
if isinstance(v, dict):
tmp = self.__dict2obj(v)

setattr(self, k, tmp)

def __dict2obj(self, dictionary):
return json.loads(json.dumps(dictionary), object_hook=CustomUserDict)
Copy link
Collaborator

@dotchetter dotchetter Sep 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have some thoughts about this method.

  1. Is there a specific reason as to why __ is used? I don't think it should be named with two leading underscores, since name mangling here is unlikely to be utilized.
    I would prefer a single _ in the method and attribute name.

  2. Is dumping the entire dictionary to a string and then reloading it again in to the custom dict class CustomUserDict really necessary? Can it not be done with a cast?

  3. I can't see self being used here. I think this should be a class method in the CustomUserDict instead, returning an instance of itself.

  4. Method names should not contain digits


def __repr__(self):
_attrs = {name: value for name, value in self.__dict__.items()}
return f"Settings({_attrs})"
Expand Down
6 changes: 6 additions & 0 deletions tests/core/mocksettings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
foo = "bar"

d = {
"k1": "v1",
"k2":{"a":"a","b":"b"}
}
Copy link
Collaborator

@dotchetter dotchetter Sep 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this file is redundant, and the relative import can be troublesome in a shipped package due to its relativity. Can the mockup dict object be placed in the test suite instead, such as in setUp, or as a property in the test suite?

26 changes: 26 additions & 0 deletions tests/core/test_settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from tests.module_helper import PyttmanInternalBaseTestCase
from pyttman.core.internals import Settings

from importlib import import_module
from . import mocksettings

class PyttmanInternalSettingsPyttmanApp(PyttmanInternalBaseTestCase):
def __init__(self, *args, **kwargs):
Copy link
Collaborator

@dotchetter dotchetter Sep 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use setUp hook in tests instead of overriding __init__. The setUp hook is left unimplemented for these suites to implement them for this purpose.

super().__init__(*args, **kwargs)
settings_names = [i for i in dir(mocksettings)
if not i.startswith("_")]
settings_config = {name: getattr(mocksettings, name)
for name in settings_names}
self.settings = Settings(**settings_config)

def test_read_settings_with_dictionary(self):

self.assertTrue(self.settings.d.k2.a == "a")
self.assertTrue(self.settings.d["k2"].a == "a")
self.assertTrue(self.settings.d["k2"]["a"] == "a")

self.assertTrue(self.settings.d.k1 == "v1")
self.assertTrue(self.settings.d["k1"] == "v1")

self.assertTrue(self.settings.foo == "bar")