Give something as follows:
import importlib
module_path = "mod"
mod = importlib.import_module(module_path, package=None)
print(mod.Foo.Bar.x)
where mod.py is:
class Foo:
class Bar:
x = 1
mypy file.py --strict raises the following error:
file.py:7: error: Module has no attribute "Foo" [attr-defined]
I'm wondering how one is supposed to go about type-hinting this, or if this is something which would typically just be ignored with # type: ignore[attr-defined] (assuming that the code is necessary, and the only options are type-hinting or ignoring the type-hint)?
Why I am using importlib in this situation
The way that importlib is being used is that there's some path:
x.y.<changes>.z
Where <changes> is dynamic, but the others are fixed. I'm confident that the module will contain the attributes which are being called, but due to <changes>, importlib is used for the import.
Which might be summarised as:
I do not know precisely which module I will be importing, but I know it will have a class
Fooin it.
importlibcan import arbitrary code – a type checker has no way of knowing what module it provides. The only option is to structurally type the entire module and hintmodwith it, which seems to defeat the point of usingimportlib.