Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a Python object is a module?

Tags:

python

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.

like image 968
hemflit Avatar asked Nov 28 '22 21:11

hemflit


2 Answers

You can use inspect.ismodule:

>>> import inspect
>>> import os
>>> os2 = object()
>>> inspect.ismodule(os)
True
>>> inspect.ismodule(os2)
False
like image 170
Blender Avatar answered Dec 06 '22 16:12

Blender


You can do:

from types import ModuleType
print isinstance(obj, ModuleType)
like image 33
karthikr Avatar answered Dec 06 '22 14:12

karthikr