Skip to content

better support for metaclass #84

@randy3k

Description

@randy3k

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 string

Changes 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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions