Created
April 3, 2019 11:27
-
-
Save vsego/2551f62028d1217dc072a9810963ccd0 to your computer and use it in GitHub Desktop.
Last-session aware class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A proof of concept: ability to have `X.f(...) == X.sess.f(...)`, but also be | |
able to use `x = X(); y = X(); x.f(...)` in the expected way. | |
""" | |
import inspect | |
class _X: | |
""" | |
We put properties and instance methods here. | |
""" | |
sess = None | |
def __init__(self, foo): | |
type(self).sess = self | |
self.foo = foo | |
def f(self, X=None): | |
print(self, X) | |
class _meta_x(type): | |
def __new__(cls, *args, **kwargs): | |
for name, f in inspect.getmembers(_X, predicate=inspect.isfunction): | |
if not name.startswith("_"): | |
setattr(cls, name, cls.__session_method(f)) | |
return super().__new__(cls, *args, **kwargs) | |
def __session_method(f): | |
def wrapped(cls, *args, **kwargs): | |
f(_X.sess, *args, **kwargs) | |
return wrapped | |
class X(object, metaclass=_meta_x): | |
""" | |
We want to use this class. | |
""" | |
def __new__(cls, *args, **kwargs): | |
return _X(*args, **kwargs) | |
print("1: ", end=""); X.f() | |
print("2: ", end=""); X.f(17) | |
print("3: ", end=""); X(1).f() | |
print("4: ", end=""); X(1).f(17) | |
print("5: ", end=""); X.f() | |
print("6: ", end=""); X.f(17) | |
# Careful: the type is not what the constructor would imply! | |
print(type(X(1)), "!=", X) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment