w3resource

Python: Get the actual module object for a given object


Get Module Object

Write a Python program to get the actual module object for a given object.

Sample Solution-1:

Python Code:

# Import the 'getmodule' function from the 'inspect' module.
from inspect import getmodule

# Import the 'sqrt' function from the 'math' module.
from math import sqrt

# Use the 'getmodule' function to get the module where the 'sqrt' function is defined.
# Then, print the module information for the 'sqrt' function.
print(getmodule(sqrt))

Sample Output:

<module 'math' (built-in)>

Flowchart:

Flowchart: Get the actual module object for a given object.

Sample Solution-2:

Python Code:

# Import the 'inspect' module.
import inspect

# Define a function named 'add' that takes two arguments, 'x' and 'y'.
def add(x, y):
    return x + y

# Use the 'inspect.getmodule' function to get the module where the 'add' function is defined.
# Then, print the module information for the 'add' function.
print(inspect.getmodule(add))

Sample Output:

<module '__main__' from '/tmp/sessions/5ced515afe46d808/main.py'>

Flowchart:

Flowchart: Get the actual module object for a given object.

For more Practice: Solve these Related Problems:

  • Write a Python program to retrieve the module object for a dynamically imported module.
  • Write a Python function to check if a given object belongs to a module.
  • Write a Python program to list all attributes and methods of a given module object.
  • Write a Python program to determine the file path of a module using its object.

Go to:


Previous: Write a Python program to sum of all counts in a collections.
Next: Write a Python program to check if an integer fits in 64 bits.

Python Code Editor:

 

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.