aleax at aleax.it
Wed Jan 2 13:31:24 CET 2002
"Giorgi Lekishvili" <gleki at gol.ge> wrote in message
news:3C337808.ECCE968E at gol.ge...
> Suppose, one has a module, which defines some set of functions.
> How can one get the names of all these functions as list entries?
You don't need to bind name all_func to anything: it gets rebound
two statements later, so this binding has no effect at all.
> import myModule
> of course, this will not work.
No, but, after the import, you could for example do:
all_func = [name for name in dir(myModule) if
this isn't QUITE what you asked since it gives you the name of every
CALLABLE object that is a module attribute: this includes functions,
builtin-functions, and classes too (and potentially more things yet,
such as instances of classes exposing a __call__ special method that
the module is trying to "masquerade", aka "pass off as", functions:-)].
If you do need to check for FUNCTIONS specifically, and rule out every
other callable object, you can to that, of course:
all_func = [name for name in dir(myModule)
if type(getattr(myModule,name)) is types.FunctionType]
However, you're "normally" quite OK with accepting "stuff masquerading
as functions" as equivalent to functions. The test for 'callable',
while maybe a bit weak, is more likely closer to what you really need,
than the test for type-identity with 'functions'. Still, it's up to you.
> What is to be done? Some special functions are to be written or, is
> there a built-in tool?
There are several built-in functions:
dir(obj) get all attributes name directly defined in obj
getattr(obj, name) get attribute value given attribute name
callable(obj) check if an object can be called as a function
type(obj) get the typeobject for an object
and language 'tools' such as list comprehensions, to put together
lists. If you do this often, you may indeed want to write a "special
function" of your own that puts together a few of these built-in tools
to give you the overall functionality that you desire.
More information about the Python-list