Suppose I have below python file structure:
\function_group
|-__init__.py
|-sub_function1
|----|__init__.py
|----|sub_sub_func1.py
|----|sub_sub_func2.py
|----|sub_sub_func3.py
|-sub_function2
|----|__init__.py
|----|sub_sub_func1.py
|----|sub_sub_func2.py
|----|sub_sub_func3.py
In each sub_sub_funcX.py
there's a list functions will collect all function name in sub_sub_funcX.py
itself,
# sub_sub_funcX.py
# and each sub_sub_funcX.py file has similiar code
import inspect
functions = inspect.getmembers(self?, inspect.isfunction) # how to write the "self" here
def bar(x, y):
return x * y
def bar1(x, y):
return x + y
My questions are
on the above code marked
"# how"
, what is the right expression for point self? Should it be a"sub_sub_funcX"
?how I can get a full list of all those [functions] when import the top module
function_group
? I means is it possible each sub_function modules can report to the top it's function list in some how when import?is there a way I can easy extend modules without adding housekeeping code in
__init__
just an easy to hook and easy to remove? for example, I change the structure like this later:
\function_group
|-__init__.py
|-sub_function1
|----|__init__.py
|----|sub_sub_func1.py
|----|sub_sub_func2.py
|----|sub_sub_func3.py
|-sub_function2
|----|__init__.py
|----|sub_sub_func1.py
|----|sub_sub_func2.py
|----|sub_sub_func3.py
|----|sub_sub_func4.py # new added
|-sub_function3 # new added
|----|__init__.py # new added
|----|sub_sub_func1.py # new added
|----|sub_sub_sub_function_31 # new sub added
|--------|__init__.py # new added
|--------|sub_sub_sub_sub_func开发者_如何学编程1.py# new added
1: You need
import inspect
import sys
inspect.getmembers(sys.modules[__name__], inspect.isfunction)
2: The best answer I can think of is to import the submodules, and inspect them in the top-level.
- No, the onus is on the top-level package (the one which is imported) to do what it needs to do. You can't import the top package and expect the sub-packages to do their thing, unless they're imported in the top-package. And since you don't want to modify your top-level init.py, that's not going to happen.
Can you tell us exactly what you're trying to do with those functions? I'm getting the feeling that there has to be a better way than this much introspection.
精彩评论