Is there a way to know where a variable was defined in python (e.g. file name)?
I’m experiencing the following problem: in one of project’s source file, there is a “print variable” statement, and variable isn’t defined in that file, and I can’t find where it is defined variable.
No, not for variables. Variables are just references to arbitrary python objects, and if you can find the variable, you have found the function, class, or the module it is defined in.
I suspect you wanted to know where python objects are defined in instead; for many objects that can be determined from the
.__file__attribute of the object. For classes, you’d have to traverse back it’s module first, for methods, traverse to it’s function, for functions, find it’s code object, for code objects, use their.co_filenameattribute, etc.Or use the
getsourcefile()function to automate that process: