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.
Example class for a strange problem passing **kwargs to a class init function, when other args are passed as keywords too.
"""
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)
# Workaround of course
TestObject(irrelevant=False, **d.__dict__)
# Does not work in Pypy...
TestObject(irrelevant=False, **d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment