__call__ in module?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Sep 27 19:54:36 EDT 2005


On Tue, 27 Sep 2005 14:19:13 -0700, ncf wrote:

> I have a feeling that this is highly unlikely, but does anyone in here
> know if it's possible to directly call a module, or will I have to wrap
> it up in a class?

Why not try it yourself? Write a quick module like this:

"""Call a module"""

def __call__():
    return "Thank you for calling."

then try to call it from an interactive session:

py> import caller
py> caller()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'module' object is not callable

With things this simple, you learn more from doing than from asking.


A better question is, if a module object has a __call__ method, shouldn't
it *be* callable? That would let you write a script, put the normal Python
idiom at the end:

if __name__ == "__main__":
    __call__(sys.argv)  # instead of "main()"

No major benefit there, we've just changed main to __call__. But
then you can call the script as a stand-alone piece of code from within
Python:

import script
result = script(my_args)


-- 
Steven.




More information about the Python-list mailing list