Reputation: 346
Say I've imported a package by doing import package
. In each of the modules within this package, there is a function called "func". Is there a way to iterate over the modules that were imported with this package, calling the function for each module?
Something along the lines of this pseudocode:
import package
for module in package:
module.func()
EDIT: solution
import inspect
import package
for name, module in inspect.getmembers(package, predicate=inspect.ismodule):
module.func()
Now it is also required that you filter out the built in modules that are returned and don't contain func implementations, but that is a separate problem altogether.
Upvotes: 1
Views: 1006
Reputation: 76
I just ran it without a for loop. However if you want to inspect multiple packages at once you´d have to loop:
import pandas as pd
import inspect
inspect.getmembers(pd, predicate=inspect.isfunction)
output (truncated):
[('array', <function pandas.core.construction.array>),
('bdate_range', <function pandas.core.indexes.datetimes.bdate_range>),
('concat', <function pandas.core.reshape.concat.concat>),
('crosstab', <function pandas.core.reshape.pivot.crosstab>),
('cut', <function pandas.core.reshape.tile.cut>),
('date_range', <function pandas.core.indexes.datetimes.date_range>),
('eval', <function pandas.core.computation.eval.eval>),
('factorize', <function pandas.core.algorithms.factorize>),
('get_dummies', <function pandas.core.reshape.reshape.get_dummies>),
('infer_freq', <function pandas.tseries.frequencies.infer_freq>),
('interval_range', <function pandas.core.indexes.interval.interval_range>),
('isna', <function pandas.core.dtypes.missing.isna>),
('isnull', <function pandas.core.dtypes.missing.isna>),
('json_normalize', <function pandas.io.json._normalize._json_normalize>),
('lreshape', <function pandas.core.reshape.melt.lreshape>),
('melt', <function pandas.core.reshape.melt.melt>),
('merge', <function pandas.core.reshape.merge.merge>),
('merge_asof', <function pandas.core.reshape.merge.merge_asof>),
Upvotes: 1