Python Forum

Full Version: Is changing processes by using match with type function impossible?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello.

I know to distinguish 'type' is usually with isinstance function, but examine this:

def what_is_it(x):
    def format():
        nonlocal x
        match type(x):
            case "<class 'float'>":
                return "a float"
            case "<class 'boolean'>":
                return "boolean"
            case "<class 'list'>":
                return "a list"
            case _:
                return f'a(n) {type(x)}\n'
    return f"{x} is {format()}."
However, this does not work properly.

>>> [what_is_it(i) for i in [False, ["a", "b"], 7.0, 7]]
["False is a(n) <class 'bool'>\n.", "['a', 'b'] is a(n) <class 'list'>\n.", "7.0 is a(n) <class 'float'>\n.", "7 is a(n) <class 'int'>\n."]
Is there any idea to let it work properly? Otherwise, is the combination of match and type no good?

Thanks.

Note: People familiar with ANSI Common Lisp would notice that what I want to do is something like typecase macro there.
I found it seems to work, I don't know whether this is a good way to do or not, though.

def what_is_it(x):
    def format():
        nonlocal x
        match type(x).__name__:
            case 'float':
                return "a float"
            case 'bool':
                return "boolean"
            case 'list':
                return "a list"
            case _:
                return f'a(n) {type(x)}\n'
    return f"{x} is {format()}."
Anyway, it gives what I want.

[what_is_it(i) for i in [False, ["a", "b"], 7.0, 7]]
['False is boolean.', "['a', 'b'] is a list.", '7.0 is a float.', "7 is a(n) <class 'int'>\n."]
Thanks.