PK!{(Bpolymorphism/__init__.pyfrom collections import UserDict from inspect import Parameter, isclass, ismethoddescriptor, signature from operator import attrgetter from types import MethodType from typing import cast, Any, Dict, List, Union from .helpers import is_overridable, sanitize_method from .types import OneTimeSetDict from .typing import FunctionOrDescriptorType __all__ = ['overload', 'Polymorphism', 'PolymorphismMeta'] class MultiMethod: def __init__(self, method: FunctionOrDescriptorType) -> None: self._methods = cast( dict, OneTimeSetDict() ) # type: Dict[tuple, FunctionOrDescriptorType] self.overload(method) def overload(self, method: FunctionOrDescriptorType) -> 'MultiMethod': m_types = [] # type: List[type] actual_method = sanitize_method(method, object()) try: sig = signature(actual_method) except ValueError: raise TypeError( 'Descriptor should save wrapped ' 'function under "__wrapped__" name' ) for param in sig.parameters.values(): if param.annotation is Parameter.empty: raise TypeError( 'Argument "{}" should be annotated'.format(param) ) if param.kind in {Parameter.VAR_KEYWORD, Parameter.VAR_POSITIONAL}: raise TypeError( 'Argument "{}" shouldn\'t be variable length'.format(param) ) if param.default is not Parameter.empty: self._methods[tuple(m_types)] = method m_types.append(param.annotation) self._methods[tuple(m_types)] = method return self def __get__(self, instance, class_=None) -> MethodType: if instance is not None: return MethodType(self, instance) else: return MethodType(self, class_) def __call__(self, instance: Any, *args, **kwargs) -> Any: call_types = tuple(map(type, args)) if kwargs: call_size = len(args) + len(kwargs) possible_types = filter( lambda t: len(t) == call_size, self._methods.keys() ) if args: possible_types = filter( lambda t: t[:len(args)] == call_types, possible_types ) methods = (self._methods[t] for t in possible_types) for method in methods: # Class object can be passed only to descriptor if isclass(instance) and not ismethoddescriptor(method): continue actual_method = sanitize_method(method, instance) sig = signature(actual_method) arguments = sig.bind(*args, **kwargs).arguments actual_types = list(map(type, arguments.values())) sig_types = list( map(attrgetter('annotation'), sig.parameters.values()) ) if actual_types == sig_types: return actual_method(**arguments) elif self._methods.get(call_types): method = self._methods[call_types] actual_method = sanitize_method(method, instance) return actual_method(*args, **kwargs) call_types = call_types + tuple(map(type, kwargs.values())) raise TypeError('Method for types {} not exists'.format(call_types)) class MultiDict(UserDict): def __setitem__(self, key: str, item: Any) -> None: value = self.get(key) if value is None or not is_overridable(value): return super().__setitem__(key, item) if not is_overridable(item): raise TypeError('Method "{}" is shaded by attribute'.format(key)) method = cast(Union[FunctionOrDescriptorType, MultiMethod], value) if not isinstance(method, MultiMethod): method = MultiMethod(method) super().__setitem__(key, method) method.overload(item) class PolymorphismMeta(type): def __new__(mcs, name, bases, dict_): return type.__new__(mcs, name, bases, dict(dict_)) @classmethod def __prepare__(mcs, name, bases): return MultiDict() class Polymorphism(metaclass=PolymorphismMeta): pass overload = MultiMethod PK!3polymorphism/helpers.pyfrom inspect import ismethoddescriptor, isfunction, isclass from types import MethodType, MemberDescriptorType, FunctionType from typing import cast, Any from .typing import AnyMethodType __all__ = ['is_overridable', 'sanitize_method'] def is_overridable(obj) -> bool: return ismethoddescriptor(obj) or isfunction(obj) def sanitize_method( method: AnyMethodType, instance: Any = object ) -> MethodType: if ismethoddescriptor(method): descriptor = cast(MemberDescriptorType, method) if not isclass(instance): return descriptor.__get__(instance, type(instance)) else: return descriptor.__get__(None, instance) elif isfunction(method) and not isclass(instance): function = cast(FunctionType, method) return MethodType(function, instance) # Something goes wrong, should never happen raise RuntimeError PK!wEEpolymorphism/types.pyfrom collections import UserDict __all__ = ['OneTimeSetDict'] class OneTimeSetDict(UserDict): def __setitem__(self, key, value): if key in self: raise TypeError( 'Overloading an existing method with {} types'.format(key) ) return super().__setitem__(key, value) PK!Cw<polymorphism/typing.pyfrom types import FunctionType, MemberDescriptorType, MethodType from typing import Union __all__ = ['AnyMethodType', 'FunctionOrDescriptorType'] FunctionOrDescriptorType = Union[FunctionType, MemberDescriptorType] AnyMethodType = Union[FunctionType, MemberDescriptorType, MethodType] PK!Uz&&$polymorphism-0.1.2.dist-info/LICENSEMIT License Copyright (c) 2018 asduj Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!HnHTU"polymorphism-0.1.2.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!Hc%polymorphism-0.1.2.dist-info/METADATAXS6BM?蝏@LoBiH2!i>4ugr%ve N:9|ZVHyI/)봩b'milkWFn7e)m;O2tVL[JtNo_Lo}ƣLĩ)Geځ:U ΍zP) %2j| 9IXiJǭmQ6*7 ţhSࢋCs񤮭9S=#~ymkkfVfPV&{[ Adǽ[>΃+燩9vfgUUL#÷m܏·(cY^׏9E7Mѽ($ W^xEZBd9IkXNEF4F+qy.Qڋ5egzݐLqxlPbe[) 9uzej*RYNӁ8#"?-o#Tjimtiad]et-{a^8ۻhr81R9!JHV\Ρ7LGRDSei+'z%ZjshTjD}n[x1mo6t,Bgz:UVJl )АJOd&.[,Cq'"*P sJ yX/n'A+O397M/Zzo )>o&Q&gJRVs%}Sy,dՊBO,<֤F}{113%2i6̤.;A]GhT7pq#e9d%[ǦA_z|e()|kje}$B<Ɲ7N7zv %\_HYBO$I0!mi GAׁB'z=ԥr6Ӄh쾨$i7u@Sp&"ݽg2Wsr-aL z̢~) i 6>lq} >M`y]`oefcʁC%"tu]5pm.YEy֝w) סNDuͨ9_gR{.M wv(ϹW>E1ooc' .%WW.d$gOƦk?a9ZbNmȹ<]qO55bUB+Ê8'Q 6YVQ dV)M ׿n\a >;&/Nr0~Fl IM{="I 8m,fjiuNO¿d0a^<3WtCLϭBV̐llc0JPVS#tBVaQJ$ F/kb4)dTʎh3DOI1VWBѵC ;⃗+ИPK!H&G8.u#polymorphism-0.1.2.dist-info/RECORD}r@{1,!VD" ^ ()SSki=7E70^3 ^|NpTvg6|OGּAQD(`m',BŨivD۴&Vlx77m:u2 {Ł#xhc24_Im P+IPiu\"%kI7fULZ5oQ9Z ad 4VgDxnMeerto\K+ |&B$2{du_DfhbI1 6uZEWʯOk=mEɌt3Øn+E׺ _PK!{(Bpolymorphism/__init__.pyPK!3polymorphism/helpers.pyPK!wEEpolymorphism/types.pyPK!Cw<Qpolymorphism/typing.pyPK!Uz&&$polymorphism-0.1.2.dist-info/LICENSEPK!HnHTU" polymorphism-0.1.2.dist-info/WHEELPK!Hc%polymorphism-0.1.2.dist-info/METADATAPK!H&G8.u##polymorphism-0.1.2.dist-info/RECORDPKX%