TransWikia.com

Python type hints: `def f(e: Union[np, tf])` for `import numpy as np`?

Stack Overflow Asked on November 20, 2021

Goal: restrict function argument to only accept the numpy or tensorflow module.

Some ideas I have, use Literal types (PEP586):

Literal["np", "tf"]

Then use globals() to find the symbol. This would work reasonably well, though obviously skips the module type check.

Is there some way I can accept either the str representation or the module itself? – Passing in the module itself gave this error:

Expected type Literal["np", "tf"], got Union[__init__.py, __init__.py] instead

But I don’t know how to create Union[__init__.py, __init__.py], e.g., this doesn’t work:

Union[Union[__init__.py, __init__.py], Literal["np", "tf"]]

One Answer

Do you need to use type checking? You could assert like so

assert module == np or module == tf, f"{module.__name__} not numpy or tensorflow"

Answered by Evan on November 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP