Skip to content

Instantly share code, notes, and snippets.

@lazyfrosch
Last active November 7, 2022 17:44
Show Gist options
  • Save lazyfrosch/2e9cb973e83bec4bb8d6d6e9ed48a723 to your computer and use it in GitHub Desktop.
Save lazyfrosch/2e9cb973e83bec4bb8d6d6e9ed48a723 to your computer and use it in GitHub Desktop.

Revisions

  1. lazyfrosch revised this gist Nov 7, 2022. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions test-dict-similar.py
    Original file line number Diff line number Diff line change
    @@ -52,5 +52,8 @@ def __init__(self, irrelevant=None, **kwargs):
    TestObject(**d)
    TestObject(False, **d)

    # Workaround of course
    TestObject(irrelevant=False, **d.__dict__)

    # Does not work in Pypy...
    TestObject(irrelevant=False, **d)
  2. lazyfrosch created this gist Nov 7, 2022.
    56 changes: 56 additions & 0 deletions test-dict-similar.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    """
    Example class for a strange problem passing **kwargs to a class init function, when other args are passed as keywords too.
    DictSimilar behaves as a wrapper around dict, to provide an object for dict structures.
    Works in CPython 3.10.8
    Does NOT work in Pypy:
    Python 3.9.12 (05fbe3aa5b0845e6c37239768aa455451aa5faba, Mar 29 2022, 08:15:34)
    [PyPy 7.3.9 with GCC 10.2.1 20210130 (Red Hat 10.2.1-11)]
    Also discussed in:
    https://github.com/ansible-collections/kubernetes.core/issues/447
    """

    class DictSimilar():
    """
    Minimal test class, based on ResourceField from kubernetes.base.dynamic.resource
    https://github.com/kubernetes-client/python/blob/master/kubernetes/base/dynamic/resource.py
    """

    def __init__(self, params):
    self.__dict__.update(**params)

    def __getitem__(self, name):
    return self.__dict__.get(name)

    def __getattr__(self, name):
    return self.__dict__.get(name, getattr(self.__dict__, name, None))

    def __setattr__(self, name, value):
    self.__dict__[name] = value

    def __iter__(self):
    for k, v in self.__dict__.items():
    yield (k, v)


    class TestObject():
    def __init__(self, irrelevant=None, **kwargs):
    print(kwargs)


    d = DictSimilar({
    "a": 1234,
    "b": "4567",
    "c": True
    })

    # Works even in Pypy
    TestObject(**d)
    TestObject(False, **d)

    # Does not work in Pypy...
    TestObject(irrelevant=False, **d)