2

I bring a few days working on python coming from Matlab and I have the next doubt:

I had a matlab program with a lot of functions defined at the end of my m-file. Matlab recognizes those functions even if I call them at the beginning and they are defined at the bottom of my code.

Now, with python, I don't know what is the best way to put the functions because python needs to know the definition of the functions before calling them. I don't want to create a new file for each function. I would like to put all functions together but I can't figure it out. I hope you can help me.

Thx,

tete
  • 81
  • 1
  • 6

3 Answers3

6

Another way you can have all the functions is to add a function that does everything you want it to do:

def main():
    #do stuff
    f()
    g()
    ...

And add this to the end of the file:

if __name__ == '__main__':
    main()

This will only execute if your file is the main file. If you import your file from another file, then it won't execute all the code in main().

Jmac
  • 308
  • 1
  • 9
  • 1
    I'd prefer this method, just because it doesn't needlessly create other files. You can always refactor functions out later if you need to share them between modules. – acjay Jul 02 '13 at 21:18
  • I like this way and it works nicely too. Thx. For me, now it's more like matlab style because I have the main code on top and the functions at the end of the file. – tete Jul 02 '13 at 22:48
2

You can put all the functions in a functions.py and include it in every document

import functions

then you can call a function by adding the prefix functions.

zurfyx
  • 31,043
  • 20
  • 111
  • 145
  • Easier than expected! Exactly using: from functions import * Thx! – tete Jul 02 '13 at 20:11
  • 3
    @tete you should shy away from using `from functions import *` as explained in http://stackoverflow.com/q/2386714/1980029. – robjohncox Jul 02 '13 at 20:55
  • 1
    @tete, if you don't want to call all functions (mentioned by @robjohncox), you can do a from `functions import function1`. That is recommended and it is used a lot. – zurfyx Jul 03 '13 at 07:41
2

Actually python does not need you to declare functions in any particular order to have them called.

For example this works fine :

def a():
  return b()

def b():
  return 1

a()
rotoglup
  • 5,223
  • 25
  • 37