Let's say I open up a large source file and see this:
print(x)
x
isn't defined in this file and there are a dozen import statements. How do I determine where x
was imported from?
CodePudding user response:
If x
is a primitive type (int
, float
, complex
, str
, bytes
, etc.) you don't really have a good way of checking it. I guess this serves as a good reminder of avoiding things such as from somemodule import *
.
If x
is an object (such as a class or a function), then you can look at x.__module__
, which will tell you the module name. There is also inspect.getmodule(x)
which will give you some more info (e.g. the exact path of the module).
CodePudding user response:
If it is a "primitive type", as Marco calls it, you could try accessing it after each import. Basic version (could be improved):
from fractions import *
try:
pi
print('fractions')
except NameError:
pass
from math import *
try:
pi
print('math')
except NameError:
pass
That reports math
. Try it online!
CodePudding user response:
When you import a module e.g. numpy: import numpy as np
you can clearly see what are numpy objects or numpy methods because you can only call numpy functions for example like this np.roll(), np.array(),...
however if you dont need the full module and only a litte part of it you import it like this
from numpy import roll
now you can call the roll function simply like this: roll()
Conclusion: If e.g. x is nowhere defined in a script it must come from an import you just need to look exactly how the module is imported