-
Notifications
You must be signed in to change notification settings - Fork 74
Open
Description
It would be interesting to better support metaclasses
Feature request
For example, one may want to create a function whoami which returns different results when running whoami(int) and whoami(str). (PS, I meant literally whoami(int), not whoami(1))
@dispatch(type(str))
def whoami(x):
print("you are a string")
@dispatch(type(int))
def whoami(x):
print("you are a int")It would work if type(str) and type(str) have different types. Unfortunately, they don't, and they are both type.
It could, however, be accomplished by using a different type function. Consider
class DataType(type):
def __instancecheck__(self, instance):
return self.t == instance
def __subclasscheck__(self, subclass):
return isinstance(subclass, DataType) and self.t == subclass.t
_data_types = {}
def MyType(t):
if isinstance(t, type) and t is not object:
if t not in _data_types:
_data_types[t] = DataType(
"{}_type".format(t.__name__),
(type,),
{"t": t, "__new__": lambda cls: cls.t})
return _data_types[t]
else:
return type(t)With this new type function, I could determine the type of str and int with a new system.
isinstance(str, MyType(str))
#> True
MyType(str) == MyType(int)
#> False
Finally, it allows me to do what I originally wanted to do
@dispatch(MyType(str))
def whoami(x):
print("you are a string")
@dispatch(MyType(int))
def whoami(x):
print("you are a int")
whoami(int)
#> you are a int
whoami(str)
#> you are a stringChanges required in multipledispatch
In the above example, I would need to replace the type of thisline by MyType though.
In all, I am requesting a customizable type function when the dispatcher is created.
Metadata
Metadata
Assignees
Labels
No labels