आप मॉड्यूल के सभी एट्रिब्यूट/मेथड प्राप्त करने के लिए `dir(module)` का उपयोग कर सकते हैं।
उदाहरण
>>> import math
>>> dir(math)
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan',
'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf',
'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum',
'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p',
'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
लेकिन जैसा कि आप देख सकते हैं, मॉड्यूल के एट्रिब्यूट (`__name__`, `__doc__`, आदि) भी सूचीबद्ध हैं। आप `isfunction` प्रीडिकेट और `getmembers(module, predicate)` का उपयोग करके इन्हें फ़िल्टर करने वाला एक सरल फ़ंक्शन बना सकते हैं।
केवल फ़ंक्शन प्राप्त करें
>>> from inspect import getmembers, isfunction
>>> import helloworld
>>> print([o for o in getmembers(helloworld) if isfunction(o[1])])
['hello_world']
नोट: यह बिल्ट-इन मॉड्यूल के लिए काम नहीं करता क्योंकि उन मॉड्यूल के लिए फ़ंक्शन का प्रकार `function` नहीं बल्कि `builtin_function_or_method` होता है।
बिल्ट-इन मॉड्यूल के लिए: isbuiltin उपयोग करें
from inspect import getmembers, isbuiltin, isfunction
def get_all_functions(module):
"""मॉड्यूल से सभी फ़ंक्शन (पायथन + बिल्ट-इन) प्राप्त करें।"""
return [name for name, obj in getmembers(module)
if isfunction(obj) or isbuiltin(obj)]
import math
print(get_all_functions(math))
# ['acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', ...]
अधिक विस्तृत: फ़ंक्शन सिग्नेचर के साथ
from inspect import getmembers, isfunction, isbuiltin, signature
def get_functions_with_sigs(module):
"""फ़ंक्शन नाम और उनके सिग्नेचर के साथ प्राप्त करें।"""
funcs = []
for name, obj in getmembers(module):
if isfunction(obj) or isbuiltin(obj):
try:
sig = signature(obj)
funcs.append(f"{name}{sig}")
except ValueError:
funcs.append(f"{name}(...signature unavailable...)")
return funcs
import math
for f in get_functions_with_sigs(math):
print(f)
क्लास मेथड के लिए
from inspect import getmembers, isfunction, ismethod, isclass
class MyClass:
def method1(self): pass
@classmethod
def method2(cls): pass
@staticmethod
def method3(): pass
# इंस्टेंस मेथड
print([n for n, o in getmembers(MyClass, isfunction)])
# ['method1', 'method3']
# सभी कॉल करने योग्य
print([n for n, o in getmembers(MyClass) if callable(o)])
# ['method1', 'method2', 'method3', '__init__', '__module__', ...]
सारांश
| विधि | प्राप्त करता है | नोट्स |
|---|---|---|
| `dir(module)` | सभी एट्रिब्यूट | निजी/डंडर शामिल |
| `inspect.getmembers(module, isfunction)` | पायथन फ़ंक्शन | बिल्ट-इन छूट जाते हैं |
| `inspect.getmembers(module, isbuiltin)` | बिल्ट-इन फ़ंक्शन | केवल C एक्सटेंशन |
| `callable()` जांच | सभी कॉल करने योग्य | क्लास, मेथड शामिल |