I had to modify extention implementation: I corrected class scope check at (3) and also added check if attribute is callable, so your extension class could have it's own usable attributes, that are acessible via self
defextension(scope_cls):def_default(_obj,_name):raiseAttributeError()# (1)
# we access the base-class of our extension class to get the class we're extending.
base_cls=scope_cls.__base__cls_name=scope_cls.__name__original_getattr=getattr(base_cls,'__getattr__',_default)def_getattr(obj,name):withsuppress(AttributeError):returnoriginal_getattr(obj,name)# (2)
# we check whether the requested attribute exists in our extension class.
# As you can see, the changes are pretty simple and straight-forward.
ifnothasattr(scope_cls,name):raiseAttributeError()# (3)
# we make the most important change -
# we check for the extension class in the scope,
# not the extension methods.
# This is the core of this change!
ifnot_is_in_scope(scope_cls,cls_name):raiseAttributeError()# (4)
# we get the required attribute from out extension class.
attribute=getattr(scope_cls,name)# if it is function, return as function
ifhasattr(attribute,'__call__'):returnfunctools.partial(attribute,obj)# return as is
returnattributecls.__getattr__=_getattrreturnscope_cls
and my example of usage:
# no defined method here
classContext:def__init__(self):self.bag=dict()@extensionclassSpecificContext(Context):SPECIFIC_KEY="SPECIFIC_KEY"defget_specific(self)->Any:# bag will be taken from base class
# SPECIFIC_KEY will be taken from extension class
returnself.bag[self.SPECIFIC_KEY]defset_specific(self,value:Any)->None:self.bag[self.SPECIFIC_KEY]=valuedeftry_use_via_extension(context:SpecificContext)->bool:# without @extension attribute this will fail
# with exception 'no such attribute "set_specific" in Context class'
context.set_specific("my-secret-here")key=context.get_specific()print("my secret is "+key)# return true because it does work :)
returnTruebase_context=Context()# of type Context
try_use_via_extension(base_context)# but will be handled as SpecificContext
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
nice article, thanks!
I tried and it works like a charm.
I had to modify
extention
implementation: I corrected class scope check at (3) and also added check if attribute is callable, so your extension class could have it's own usable attributes, that are acessible viaself
and my example of usage: