I need to test if a variable is a module or not. How to do this in the cleanest way?
I need this for initializing some dispatcher function and I want that the function can accept either dict or module as an argument.
Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.
The dir() function is used to find out all the names defined in a module. It returns a sorted list of strings containing the names defined in a module. In the output, you can see the names of the functions you defined in the module, add & sub .
The type() function takes in an argument and returns the type of teh object. Apart from this method the isinstance() function can check if an argument is an instance of a particular class or type.
>>> import os, types
>>> isinstance(os, types.ModuleType)
True
(It also works for your own Python modules, as well as built-in ones like os
.)
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