Python get function path

Finding the filename and file path of a function in Python

I have large number of python files where classes are also inheriting and overriding methods. I am tracking calls of the functions. Is there a way I can get the details of the function (where it is located in which file) without the actual call of the function (for example, just by passing object and function name)? Not to forget that objects are dynamic. So just listing all function names of the project isn’t useful. File 1:

class ABC(DEF): def Start(self): pass 
class XYZ(DEF): def Start(self): pass 
class PQR(AQZ): def Activity(self): obj = ABC() # How to know in which file, the function Start is defined obj.Start() 

1 Answer 1

Take a look at the inspect module. It’s not always going to work (builtins implemented in C won’t necessarily have line numbers, or even associated files, since some modules like sys are baked into the core interpreter, not distributed as separate files), but it’s the closest you’re going to get to what you’re looking for.

Updating your example to provide info on the origin of things:

import inspect class PQR(AQZ): def Activity(self): obj = ABC() # How to know in which file, the function Start is defined try: _, lineno = inspect.getsourcelines(obj.Start) srcfile = inspect.getsourcefile(obj.Start) except TypeError: print(" is a built-in".format(obj.Start)) else: print(" comes from , line <>".format(obj.Start, srcfile, lineno)) obj.Start() 

Источник

How to get the path of a function in python?

In Python, it is sometimes useful to obtain the path of a function in order to inspect or manipulate it. One use case for this could be debugging, where you want to see the source code of a function to understand how it works or to check for errors. Another use case could be testing, where you want to make sure that the function you are calling is the one you expect it to be. In this tutorial, we will show you a few different ways to get the path of a function in Python.

Method 1: Using the file attribute

To get the path of a function in Python using the __file__ attribute, you can follow these steps:

def my_function(): print("Hello world!")
import os function_path = os.path.abspath(__file__)

Here is the complete code:

import os def my_function(): print("Hello world!") function_path = os.path.abspath(__file__) print(function_path)

This will output the path of the module that contains the function. Note that the __file__ attribute returns the path of the module, not the function itself.

Читайте также:  Python остаток по модулю

Method 2: Using the inspect module

Using the inspect module, you can get the path of a function in Python by following these steps:

file_path = inspect.getfile(my_function)
  1. Use the inspect.getsourcefile() function to get the path of the source file that contains the function:
source_file_path = inspect.getsourcefile(my_function)
module = inspect.getmodule(my_function)
source_code, line_number = inspect.getsourcelines(my_function)
import inspect def my_function(): pass file_path = inspect.getfile(my_function) source_file_path = inspect.getsourcefile(my_function) module = inspect.getmodule(my_function) source_code, line_number = inspect.getsourcelines(my_function)

Note that the getfile() and getsourcefile() functions return the path of the file as a string, while the getmodule() function returns the module object. The getsourcelines() function returns the source code of the function as a list of strings, along with the line number where the code starts.

These functions can be useful for debugging and introspection purposes, such as finding the location of a function in your codebase or inspecting the source code of a function at runtime.

Method 3: Using the built-in locals() function

To get the path of a function in Python using the built-in locals() function, follow these steps:

def my_function(): print("Hello World!")
func_obj = local_vars.get('my_function')
  1. Once you have the function object, use the module attribute to get the name of the module that the function is defined in:
module_name = func_obj.__module__
function_name = func_obj.__name__
function_path = module_name + '.' + function_name

Here is the complete code:

def my_function(): print("Hello World!") local_vars = locals() func_obj = local_vars.get('my_function') module_name = func_obj.__module__ function_name = func_obj.__name__ function_path = module_name + '.' + function_name print(function_path)

Note that the output may vary depending on the name of your module and function.

Method 4: Using the pkgutil module

To get the path of a function in Python using the pkgutil module, you can follow these steps:

def my_function(): print("Hello, World!")
module = pkgutil.getmodule(my_function)
import pkgutil def my_function(): print("Hello, World!") module = pkgutil.getmodule(my_function) path = module.__file__ print(path)

Note: Replace /path/to/my/module.py with the actual path of your module.

Источник

How to find where a function was imported from in Python?

Why are you using from bar import * ? Why do this? This specific syntax is what causes your problem, so why do it?

4 Answers 4

foo.__module__ should return bar

If you need more info, you can get it from sys.modules[‘bar’] , its __file__ and __package__ attributes may be interesting.

This package attribute is really cool, but seems to be unavailable. Is it available in python 2.5.2?

Ok, so I researched the package thing a bit. What I can’t tell is whether the value is added by default, or if I have to specify something. I tried importing an empty module («z.xx»), and z.xx.__package__ returned None. Am I doing something wrong?

Not sure, I can’t seem to get it set either. It seems the runpy module is the only one actually using it. What information did you hope to get from it?

Читайте также:  Value object to json java

Using the from . import * syntax is a bad programming style precisely because it makes it hard to know where elements of your namespace come from.

+1 because this is a valid point, although it may not solve the problem (if the questioner wants to know where the function came from programmatically, having from bar import foo is basically the same)

If you have IPython, you can also use ? :

In[16]: runfile? Signature: runfile(filename, args=None, wdir=None, is_module=False, global_vars=None) Docstring: Run filename args: command line arguments (string) wdir: working directory File: /Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_umd.py Type: function 
In[17]: runfile.__module__ Out[17]: '_pydev_bundle.pydev_umd' 

Источник

How to find file where function is defined from Python command line

Let’s say I want to explore import statements in Python. How, from the Python command line, can I find the file in which import is defined? Note I am working in Python 2.7.6 (iPython) in Windows 7. For most objects, just entering the object name is enough. For instance:

But you cannot do the same with basic commands like import . I have tried searching my Python folder but unsurprisingly don’t get something as simple as C:\Anaconda\lib\import.py . Is there a simple way to find out where such statements are defined (I realize much of the time it will be in c-code, but that is what I am after)? Update (5/27/14) It seems people think it cannot be done in any simple way with a built-in command. However, if your life depended on it, you could write up some inelegant grep-type function in Python, no?

I believe import is implemented in C, so you’d need to find where that is in the actual Python source. However, starting with Python 3.1, there is the importlib module, which provides a pure Python implementation of import : docs.python.org/3/library/importlib.html

So there is no way to find out what C file it is defined in, from the Python command line? Not sure why this was downvoted. This is something most IDEs for C/C++ let you do pretty easily.

2 Answers 2

import isn’t a module the way that os is. Instead, it’s a statement .

So my way doesn’t work, but is there a way to find the file where import is defined? Is it in Python’s C code, and if so is there a way to find where, from the python command line?

I wan to track down the source code that implements a function, so I can study the guts of the language. The example is actually immaterial. It could be «print» or any other command.

Ah. Modifying the link @dano posted above, you might want to check out hg.python.org/cpython/file/db302b88fdb6/Python for a variety of internal implementations.

That is helpful. One specific I want to know is the details about how init.py files are used in the import process.

Читайте также:  Python requests get all cookies

When you call os after importing, it prints the path to the file because it is a module. Instead, import is a statement:

>>> import math >>> math >>> import File "", line 1 import ^ SyntaxError: invalid syntax >>> 

Just in case you feel like you needed to know, here are the other statements that do similar things when called blank:

>>> with File "", line 1 with ^ SyntaxError: invalid syntax >>> yield File "", line 1 SyntaxError: 'yield' outside function >>> return File "", line 1 SyntaxError: 'return' outside function >>> continue File "", line 1 SyntaxError: 'continue' not properly in loop >>> import File "", line 1 import ^ SyntaxError: invalid syntax >>> raise Traceback (most recent call last): File "", line 1, in TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType >>> assert File "", line 1 assert ^ SyntaxError: invalid syntax >>> del File "", line 1 del ^ SyntaxError: invalid syntax >>> break File "", line 1 SyntaxError: 'break' outside loop >>> 

Источник

Get function import path

How to get from object f information about import — ‘pack.mod’ I can get it using f.__module__ but if function def in module where i get this attribute ( f.__module__ ) it return ‘__main__’ . But i need real path here — ‘pack.mod’ I found this way to get this information:

inspect.getmodule(f).__file__ 

then i can sub start path from sys.path , replace / on . and get path like — ‘pack.mod’ But may be exist some more convenient way?

3 Answers 3

What inspect.getmodule(f) does internally, per inspect.py’s sources, is essentially sys.modules.get(object.__module__) — I wouldn’t call using that code directly «more convenient», though (beyond the «essentially» part, inspect has a lot of useful catching and correction of corner cases).

Edit: reading between the lines it seems the OP is trying to do something like

and within bla.py (which is thus being run as __main__ ) determine «what from or import statement could a different main script use to import this function from within me?».

Problem is, the question is ill-posed, because there might not be any such path usable for the purpose (nothing guarantees the current main script’s path is on sys.path when that different main script gets run later), there might be several different ones (e.g. both /foo/bar and /foo/bar/baz might be on sys.path and /foo/bar/baz/__init__.py exist, in which case from baz.bla import f and from bla import f might both work), and nothing guarantees that some other, previous sys.path item might not «preempt» the import attempt (e.g., say /foo/bar/baz is on sys.path , but before it there’s also /fee/fie/foo , and a completely unrelated file /fee/fie/foo/bla.py also exists — etc, etc).

Whatever the purpose of this kind of discovery attempt, I suggest finding an alternative architecture — e.g., one where from baz.bla import f is actually executed (as the OP says at the start of the question), so that f.__module__ is correctly set to baz.bla .

Источник

Оцените статью