Skip to content

Instantly share code, notes, and snippets.

@a-recknagel
Last active August 14, 2019 08:06
Show Gist options
  • Save a-recknagel/5789e4ef887b1b9624538ce448eef74c to your computer and use it in GitHub Desktop.
Save a-recknagel/5789e4ef887b1b9624538ce448eef74c to your computer and use it in GitHub Desktop.
descriptors #1
def a(self):
return self
# write, and optionally modify class A in a way where the following will work
inst = A()
print(inst.sub.a() is inst) # True
# ------------------------------------- instance methods through class binding
# if there were no subspace, this would just work:
class A:
pass
A.a = a
# we are trying to duplicate the things that are happening under the hood here
# as a bonus, the binding happens on class level, so we don't need an __init__
# -------------------------------------------------- Aran Fey's ProxyNamespace
class ProxyNamespace:
def __init__(self, **attrs):
self._attrs = attrs
def __get__(self, inst, owner):
return Proxy(self._attrs, inst)
class Proxy:
def __init__(self, namespace, this):
self.__namespace = namespace
self.__this = this
def __getattr__(self, attr):
obj = self.__namespace[attr]
if hasattr(obj, '__get__'):
obj = obj.__get__(self.__this, type(self.__this))
return obj
class A:
sub = ProxyNamespace(a=a)
# ---------------------------------------------- using MethodType and __init__
from types import SimpleNamespace, MethodType
class A:
def __init__(self):
self.sub = SimpleNamespace('a'=MethodType(a, self))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment