pythonevalisinstance

isinstance with string representing types


isinstance("my string", "str | int")
isinstance("my string", "list")

Is there a way to check the type of a variable ("my string" in this case) based on a valid type which is stored as a string?

I don't need to import the type, I know it's builtin (int / str / float / etc).

The naive approach would be to call eval(), but that's of course unsafe. Is there a safe way to do this other than using regex/string splitting to extract individual types and matching them to their evaluated types in a huge if/else block?


Solution

  • For built-in types, you can do a lookup in the builtins module:

    >>> import builtins
    >>> getattr(builtins, 'str')
    <class 'str'>
    

    And for classes you've defined in your own code there's the globals() dictionary:

    >>> class Foo:
    ...     pass
    ...
    >>> globals()['Foo']
    <class '__main__.Foo'>
    

    Note that this doesn't handle union or generic types.