Sunday, April 17, 2011

How to include external Python code to use in other files?

If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)?

So if I have:

[Math.py]
def Calculate ( num )

How do I call it like this:

[Tool.py]
using Math.py

for i in range ( 5 ) :
    Calculate ( i )
From stackoverflow
  • If you use:

    import Math
    

    then that will allow you to use Math's functions, but you must do Math.Calculate, so that is obviously what you don't want.

    If you want to import a module's functions without having to prefix them, you must explicitly name them, like:

    from Math import Calculate, Add, Subtract
    

    Now, you can reference Calculate, Add, and Subtract just by their names. If you wanted to import ALL functions from Math, do:

    from Math import *
    

    However, you should be very careful when doing this with modules whose contents you are unsure of. If you import two modules who contain definitions for the same function name, one function will overwrite the other, with you none the wiser.

  • You will need to import the other file as a module like this:

    import Math
    

    If you don't want to prefix your Caulculate function with the module name then do this:

    from Math import Calculate
    

    If you want to import all members of a module then do this:

    from Math import *
    

    Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.

    S.Lott : +1: Quote documentation.
  • http://docs.python.org/tutorial/index.html use it!

0 comments:

Post a Comment