ZnTrack
ZnTrack copied to clipboard
Improve `load` method
Currently there are (at least) two things missing:
node = SomeNode(name="abc")
node.load() # this will return SomeNode.load() and NOT SomeNode.load("abc")
in place is not possible:
node.load() # will just return something
Maybe have node.load_() as an inplace operation?
Example of this could look like:
class ClassOrSelf:
"""Always pass 'self' to the method
This will always create and instance of the decorated class
- if called from the class instance nothing changes
- if called from a class it will create an instance and pass it to the method as 'self'
"""
def __init__(self, func):
self._func = func
self._name = None
self._owner = None
def __set_name__(self, owner, name):
# I only use a class here, because I need access to the "owner"
self._name = name
self._owner = owner
def __get__(self, obj, objtype):
@functools.wraps(self._func)
def func(*args, **kwargs):
"""Wrapper Function"""
if isinstance(obj, self._owner):
instance = obj
else:
instance = self._owner()
return self._func(instance, *args, **kwargs)
return func
class MyClass:
def __init__(self, name = None):
self.name = name
@ClassOrSelf
def load(self, name=None, inplace=False):
"""LOAD"""
if inplace:
if name is not None:
self.name = name
return self
cls = type(self)
return cls(name=self.name if name is None else name)