Get Qualified Path to Function in Shared Scripts

How do you get the qualified path to a function?

ex:
my ignition structure is...

shared/
    outer_mod/
         inner_mod/
             func()

qualified path should be...

shared.outer_mod.inner_mod.func

Starting with func? I don’t think you can. Functions are first-class objects in python, and don’t have any knowledge of the dictionaries/ mappings in which they are placed.

Well, you can get their closure chain, i think, but that will only get you their script, not any outer modules.

This is hacky, but the following works…

def func_qpath(func):
	mqpath = func.func_code.co_filename.split(':', 1)[1].rsplit('>', 1)[0]
	if hasattr(func, 'im_self'):
		mqpath += '.' + func.im_self.__name__
	return '.'.join((mqpath, func.__name__))

co_filename would return ‘<module:shared.outer_mod.inner_mod>’, so it just needs to be parsed.

UPDATE:
Added check for im_self to see if method is part of a class. Note that this will fail if you have nested classes as it would only show the innermost class in the path.

ex:

class A(object):
    class B(object):
        def func(self):
            pass

path would be...

shared.outer_mod.inner_mod.B.func
1 Like