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 6 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
22 changes: 19 additions & 3 deletions 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,7 +35,6 @@ def depr_graceful(message: str, version: str):
out = f"{message} - This was deprecated in version {version}."
warnings.warn(out, DeprecationWarning)


class Settings:
"""
Dataclass holding settings configured in the settings.py
Expand All @@ -48,7 +50,8 @@ class Settings:
aren't valid settings.
"""

def __init__(self, **kwargs):
def __init__(self, dictionary={}, **kwargs):
Copy link
Collaborator

@dotchetter dotchetter Sep 24, 2023

Choose a reason for hiding this comment

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

⚠️ This will cause a memory leak ⚠️

The problem is that in Python, default keyword arguments are parsed once, not for each call.
The argument default dictionary={} statement, is creating one dictionary used over and over again for every call. The same is true for anything non-primitive. It could cause serious implications where multiple instances of this class will share the same dictionary memory reference.

An example

If you create multiple instances of a class with this syntax, this is the result of the leak:

class A:
    def __init__(self, dictionary={})
        self.dictionary = dictionary

first = A()
second = A()

first.dictionary["foo"] = "bar"

# leak in plain sight
print(second.dictionary["foo"]
>>> "bar"

# cross-mutation
second.dictionary["foo"] = None

print(first.dictionary)
>>> None

print(first.dictionary is second.dictionary)
>>> True  # Not what we want :) 

For an example, see this stack overflow post

To fix this, use the default argument None as:

def foo(data=None):
   if data is None:
      data = {}  # Created in the function scope, fixes the issue

self.__dict__.update(dictionary)
self.APPEND_LOG_FILES: bool = True
self.MIDDLEWARE: dict | None = None
self.ABILITIES: list | None = None
Expand All @@ -60,14 +63,27 @@ 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 __getitem__(self, item):
return self.__dict__[item]

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 = Settings._dict_to_object(v)

setattr(self, k, tmp)

def __repr__(self):
_attrs = {name: value for name, value in self.__dict__.items()}
return f"Settings({_attrs})"

@staticmethod
def _dict_to_object(dictionary):
return json.loads(json.dumps(dictionary), object_hook=Settings)

def _generate_name(name):
"""
Expand Down
32 changes: 32 additions & 0 deletions tests/core/test_settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from tests.module_helper import PyttmanInternalBaseTestCase
from pyttman.core.internals import Settings

from importlib import import_module
import pytest

@pytest.fixture
def mockSettings():

mock_settings = {
"d":{
"k1":"v1",
"k2":{
"a":"a",
"b":"b"
}
},
"foo":"bar"
}

return Settings(**mock_settings)

def test_read_settings_with_dictionary(mockSettings):
assert mockSettings.d.k2.a == "a"
assert mockSettings.d["k2"].a == "a"
assert mockSettings.d["k2"]["a"] == "a"

assert mockSettings.d.k1 == "v1"
assert mockSettings.d["k1"] == "v1"

assert mockSettings.foo == "bar"