Python modules are objects too. So I would imagine it could be possible to test if a given object is a module(/package) this way:
>>> import sys, os, my_module
>>> isinstance(sys, ModuleClass)
True
>>> isinstance(os, ModuleClass)
True
>>> isinstance(my_module, ModuleClass)
True
>>> isinstance(5, ModuleClass)
False
Except "ModuleClass" is just a name I invented and I can't find in the docs if anything like it actually exists and what it's called.
Is there such a class at all? Is it somewhere in the docs that I've missed?
If not, is there another way to see if an object is a module? Even better if it's implementation-agnostic.
(I'm using Python 2.7, but I guess it would also be interesting to know if 3.x has some new solution.)
It sounds like hasattr(obj, '__package__')
(PEP 366) is a possible stopgap, but AFAICT there's no special reason to feel sure that some future update won't put __package__
into some other, totally unrelated objects. I'd prefer a solution that feels a bit more robust.
You can use inspect.ismodule
:
>>> import inspect
>>> import os
>>> os2 = object()
>>> inspect.ismodule(os)
True
>>> inspect.ismodule(os2)
False
You can do:
from types import ModuleType
print isinstance(obj, ModuleType)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With