Best way to put functions python - python

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,

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().

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.

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()

Related

Python 3 Functions not defined until run in a different part of the code?

I have just been programming in python, and have been looking to just make simple programs to start getting a better understanding.
I am busy writing a rock paper scissors text game and to work out the games winner/looser etc I created a function. For a while I when I ran my program I kept getting an error when the function was called, it was that my function was not defined. My function was below my initial code.
However I for some reason moved my function to the top of my code under my global variable declarations, and now my function executes perfectly.
Why is this the case? is there a way I can have my functions below my main code but not get the error of my function being undefined. Would I just need to declare my function before and then call it later, if so, how would I declare an empty function?
I would love to understand so any help would be greatly appreciated.
Why is this the case?
Because that's the way Python works - all the code at the top-level of a module or script is executed sequentially, so functions are only defined after the def statement has been executed.
You have to understand that in Python everything is an object, including functions, classes etc, so the def statement is mostly a syntactic sugar that creates a function object (from the def block) and binds it to the function name, IOW a function is just another global variable in your module or script - and you wouldn't expect to be able to use a variable before you defined it, would you ?
is there a way I can have my functions below my main code but not get the error of my function being undefined.
Yes quite simply by putting your "main code" in a function and call this function at the end of the script:
import something
import another thing
def main():
bar = foo()
print("the answer is {}".format(bar))
def foo():
return 42
# this makes sure the main function will only be executed
# when using your .py file as a script, not when importing
# it as a module.
if __name__ == "__main__":
main()
Function has to be defined first before it is called.You have to define a function and afterwards function can be called anywhere in the program.
This is how Python works,in this all the things executes in a sequence.

global name is not defined even though it is? [duplicate]

I am new to Python so please don't flame me if the question is too basic :)
I have read that Python is executed from top - to - bottom.
If this is the case, why do programs go like this:
def func2():
pass
def func1():
func2()
def func():
func1()
if __name__ == '__main__':
func()
So from what I have seen, the main function goes at last and the other functions are stacked on top of it.
Am I wrong in saying this? If no, why isn't the main function or the function definitions written from top to bottom?
EDIT: I am asking why I can't do this:
if __name__ == '__main__':
func()
def func1():
func2()
Isn't this the natural order? You keep on adding stuff at the bottom, since it is executed from top to bottom.
The defs are just creating the functions. No code is executed, other than to parse the syntax and tie functions to those names.
The if is the first place code is actually executed. If you put it first, and call a function before it is defined, the result is a NameError. Therefore, you need to put it after the functions are defined.
Note that this is unlike PHP or JavaScript, where functions are 'hoisted' - any function definitions are processed and parsed before everything else. In PHP and JavaScript, it's perfectly legal to do what you are saying and define functions in the source lower down than where they are called. (One detail in JS is that functions defined like function(){} are hoisted, while functions defined like var func1=function(){}; are not. I don't know how it works with anonymous functions in PHP 5.3 yet).
See, in this, cat() will print correctly, and yip() gives you a NameError because the parser hasn't gotten to the definition of yip() at the time you call it.
def cat():
print 'meowin, yo'
cat()
yip()
def yip():
print 'barkin, yall'
meowin, yo
Traceback (most recent call last):
File "cat.py", line 5, in
yip()
NameError: name 'yip' is not defined
Python is executed from top to bottom, but executing a "def" block doesn't immediately execute the contained code. Instead it creates a function object with the given name in the current scope. Consider a Python file much like your example:
def func2():
print "func2"
def func1():
func2()
def func():
func1()
if __name__ == '__main__':
func()
What happens when this script is executed is as follows:
Firstly, a function object is created and bound to the name "func2" in the global scope. Then a function object is created and bound to the name "func1" in the global scope. Then one called "func". Then the "if" statement is executed, the condition is true and the "func()" statement is executed. At this point "func" is a function object found in the global scope, so it is invoked and its code runs. That code contains the "func1()" statement, which is resolved to a call to the "func1" function, and so on.
If you put the "if" statement at the top then when it executes there would not yet be anything defined with the name "func", so you would get an error. The important thing to recognise is that the "def" statement is itself a statement that is executed. It is not like in some other languages where definitions are a separate sort of declaration with no order of execution.
Also note that so long as the "if __name__..." bit is at the end of the file, it doesn't really matter what order the other declarations are in, since by the time any of them are called all of the "def"s will have already been executed.
Python does, in general, process commands from top to bottom. However, a function call will cause Python to execute that function, and continue downward only after that call has ended.
In your example, the Python interpreter executes the following steps:
Define func2.
Define func1.
Define func.
Process if statement if __name__ == '__main__':.
Call the func function (since the condition is true).
Call the func1 function (because that's what func does).
Call the func2 function (because that's what func1 does).
End, because after finishing the call to func2 it has also finished calling func1 and therefore has finished calling func, which was the final statement in the code.
It's also worth noting that you can have function calls written occur "before they're defined", as long as they aren't executed. Mentioning this here as it's a common new-to-python error. None of the other examples demonstrate this "it's ok, in one way" behavior. (though not really recommended)
def hi():
pie()
#hi() cannot be called here, doesn't work because hi depends on pie
def pie():
print('hi pie')
hi() # it's ok to call here!
You can even go a little further (slightly silly example, but I believe it clarifies the example)
runIt = False
def hi():
if runIt:
pie()
hi() #now ok, as the code won't call pie.
runIt = True
#hi() #wouldn't be ok as now the code will call pie.
def pie():
print('hi pie')
hi() # ok here too!
The if __name__ == "__main__" part goes at the end, because presumably whatever your main function does will need all the other definitions in the script. If there were any other function definitions below the main block, then it would not be possible for them to be used in there, since they haven't been seen by the interpreter at that point.
def statements simply define a function - they don't actually run it until the function is invoked. Hence why they generally come before whatever code uses them - they set the function up to be used in the future.
There's no hard requirement that def statements come before anything else, it's just fairly common to put the __main__ code at the bottom (among other things, it makes it clear what's in that section and what isn't, since anything below the if is part of that section). It also makes sure whatever you want to call from the section has already been def'd.
For the second part of your question (Style of coding in Python), I would take a look at PEP 8, which provides a style guide written by Guido van Rossum (the BFDL himself!) and provides the basics of writing Pythonic code.
It's true that the convention is to put the "main" function just above the "if __name__ == '__main__'" statement at the end of the file. I think that this is because we usually want functions to be near to their calling sites.
As for the called function coming above the calling function, I think that this is just a result of refactoring. At least in my case, I tend to write a function, and then take out bits of code to put into sub-functions, which I put on top so that I can see better.
This is just a primitive form of code organization. If there's a stronger cohesive unit, I'd be tempted to pull those functions into their own module.
There is two points that you need to know :
The main condition is to block the prevent code from being run when
the module is imported. In our case, the condition is true because
our file is not imported.
The code is working as follows :
Define func2
Define func1
Define func
Process if statement if __name__ == '__main__': (which in our case is True)
Call the func function
Call the func1
Call the func2 function
return the result(print the message func2)
End

function call in python

I wrote a function and I try to call it but it gives me error
NameError: name 'fun' is not defined
Example:
(p1,p2) = fun(price1,price2)
def fun(price1,price2):
do something
You have to define functions before you can call them. Function definitions in Python are executable statements like any other, and are executed in the order they occur in the source file. Move your def fun block up ahead of the place where you call it.
In a standalone script like this, you'll have to define the function before you call it. So just change it to:
def fun(price1,price2):
do something
(p1,p2) = fun(price1,price2)
Looks to me like the interpreter is running the the line of code calling the function before it is defining the function. You need to switch them around, or else wrap the function call code itself in a function like main() and call that after everything is defined.
If this is a standalone script, then you need to call fun after you have defined it.
def fun(price1,price2):
do something
(p1,p2) = fun(price1,price2)

Order of execution and style of coding in Python

I am new to Python so please don't flame me if the question is too basic :)
I have read that Python is executed from top - to - bottom.
If this is the case, why do programs go like this:
def func2():
pass
def func1():
func2()
def func():
func1()
if __name__ == '__main__':
func()
So from what I have seen, the main function goes at last and the other functions are stacked on top of it.
Am I wrong in saying this? If no, why isn't the main function or the function definitions written from top to bottom?
EDIT: I am asking why I can't do this:
if __name__ == '__main__':
func()
def func1():
func2()
Isn't this the natural order? You keep on adding stuff at the bottom, since it is executed from top to bottom.
The defs are just creating the functions. No code is executed, other than to parse the syntax and tie functions to those names.
The if is the first place code is actually executed. If you put it first, and call a function before it is defined, the result is a NameError. Therefore, you need to put it after the functions are defined.
Note that this is unlike PHP or JavaScript, where functions are 'hoisted' - any function definitions are processed and parsed before everything else. In PHP and JavaScript, it's perfectly legal to do what you are saying and define functions in the source lower down than where they are called. (One detail in JS is that functions defined like function(){} are hoisted, while functions defined like var func1=function(){}; are not. I don't know how it works with anonymous functions in PHP 5.3 yet).
See, in this, cat() will print correctly, and yip() gives you a NameError because the parser hasn't gotten to the definition of yip() at the time you call it.
def cat():
print 'meowin, yo'
cat()
yip()
def yip():
print 'barkin, yall'
meowin, yo
Traceback (most recent call last):
File "cat.py", line 5, in
yip()
NameError: name 'yip' is not defined
Python is executed from top to bottom, but executing a "def" block doesn't immediately execute the contained code. Instead it creates a function object with the given name in the current scope. Consider a Python file much like your example:
def func2():
print "func2"
def func1():
func2()
def func():
func1()
if __name__ == '__main__':
func()
What happens when this script is executed is as follows:
Firstly, a function object is created and bound to the name "func2" in the global scope. Then a function object is created and bound to the name "func1" in the global scope. Then one called "func". Then the "if" statement is executed, the condition is true and the "func()" statement is executed. At this point "func" is a function object found in the global scope, so it is invoked and its code runs. That code contains the "func1()" statement, which is resolved to a call to the "func1" function, and so on.
If you put the "if" statement at the top then when it executes there would not yet be anything defined with the name "func", so you would get an error. The important thing to recognise is that the "def" statement is itself a statement that is executed. It is not like in some other languages where definitions are a separate sort of declaration with no order of execution.
Also note that so long as the "if __name__..." bit is at the end of the file, it doesn't really matter what order the other declarations are in, since by the time any of them are called all of the "def"s will have already been executed.
Python does, in general, process commands from top to bottom. However, a function call will cause Python to execute that function, and continue downward only after that call has ended.
In your example, the Python interpreter executes the following steps:
Define func2.
Define func1.
Define func.
Process if statement if __name__ == '__main__':.
Call the func function (since the condition is true).
Call the func1 function (because that's what func does).
Call the func2 function (because that's what func1 does).
End, because after finishing the call to func2 it has also finished calling func1 and therefore has finished calling func, which was the final statement in the code.
It's also worth noting that you can have function calls written occur "before they're defined", as long as they aren't executed. Mentioning this here as it's a common new-to-python error. None of the other examples demonstrate this "it's ok, in one way" behavior. (though not really recommended)
def hi():
pie()
#hi() cannot be called here, doesn't work because hi depends on pie
def pie():
print('hi pie')
hi() # it's ok to call here!
You can even go a little further (slightly silly example, but I believe it clarifies the example)
runIt = False
def hi():
if runIt:
pie()
hi() #now ok, as the code won't call pie.
runIt = True
#hi() #wouldn't be ok as now the code will call pie.
def pie():
print('hi pie')
hi() # ok here too!
The if __name__ == "__main__" part goes at the end, because presumably whatever your main function does will need all the other definitions in the script. If there were any other function definitions below the main block, then it would not be possible for them to be used in there, since they haven't been seen by the interpreter at that point.
def statements simply define a function - they don't actually run it until the function is invoked. Hence why they generally come before whatever code uses them - they set the function up to be used in the future.
There's no hard requirement that def statements come before anything else, it's just fairly common to put the __main__ code at the bottom (among other things, it makes it clear what's in that section and what isn't, since anything below the if is part of that section). It also makes sure whatever you want to call from the section has already been def'd.
For the second part of your question (Style of coding in Python), I would take a look at PEP 8, which provides a style guide written by Guido van Rossum (the BFDL himself!) and provides the basics of writing Pythonic code.
It's true that the convention is to put the "main" function just above the "if __name__ == '__main__'" statement at the end of the file. I think that this is because we usually want functions to be near to their calling sites.
As for the called function coming above the calling function, I think that this is just a result of refactoring. At least in my case, I tend to write a function, and then take out bits of code to put into sub-functions, which I put on top so that I can see better.
This is just a primitive form of code organization. If there's a stronger cohesive unit, I'd be tempted to pull those functions into their own module.
There is two points that you need to know :
The main condition is to block the prevent code from being run when
the module is imported. In our case, the condition is true because
our file is not imported.
The code is working as follows :
Define func2
Define func1
Define func
Process if statement if __name__ == '__main__': (which in our case is True)
Call the func function
Call the func1
Call the func2 function
return the result(print the message func2)
End

Make function definition in a python file order independent [duplicate]

This question already has answers here:
How do I forward-declare a function to avoid `NameError`s for functions defined later?
(17 answers)
Closed 8 months ago.
I use Python CGI. I cannot call a function before it is defined.
In Oracle PL/SQL there was this trick of "forward declaration": naming all the functions on top so the order of defining doesn't matter.
Is there such a trick in Python as well?
example:
def do_something(ds_parameter):
helper_function(ds_parameter)
....
def helper_function(hf_parameter):
....
def main():
do_something(my_value)
main()
David is right, my example is wrong.
What about:
<start of cgi-script>
def do_something(ds_parameter):
helper_function(ds_parameter)
....
def print_something():
do_something(my_value)
print_something()
def helper_function(hf_parameter):
....
def main()
....
main()
Can I "forward declare" the functions at the top of the script?
All functions must be defined before any are used.
However, the functions can be defined in any order, as long as all are defined before any executable code uses a function.
You don't need "forward declaration" because all declarations are completely independent of each other. As long as all declarations come before all executable code.
Are you having a problem? If so, please post the code that doesn't work.
In your example, print_something() is out of place.
The rule: All functions must be defined before any code that does real work
Therefore, put all the statements that do work last.
An even better illustration of your point would be:
def main():
print_something()
....
def do_something(ds_parameter):
helper_function(ds_parameter)
....
def print_something():
do_something(my_value)
def helper_function(hf_parameter):
....
main()
In other words, you can keep your definition of main() at the top, for editing convenience -- avoiding frequent scrolling, if most of the time is spent editing main.
Assuming you have some code snippet that calls your function main after it's been defined, then your example works as written. Because of how Python is interpreted, any functions that are called by the body of do_something do not need to be defined when the do_something function is defined.
The steps that Python will take while executing your code are as follows.
Define the function do_something.
Define the function helper_function.
Define the function main.
(Given my assumption above) Call main.
From main, call do_something.
From do_something, call helper_function.
The only time that Python cares that helper_function exists is when it gets to step six. You should be able to verify that Python makes it all the way to step six before raising an error when it tries to find helper_function so that it can call it.
I've never come across a case where "forward-function-definition" is necessary.. Can you not simply move print_something() to inside your main function..?
def do_something(ds_parameter):
helper_function(ds_parameter)
....
def print_something():
do_something(my_value)
def helper_function(hf_parameter):
....
def main()
print_something()
....
main()
Python doesn't care that helper_function() is defined after it's use on line 3 (in the do_something function)
I recommend using something like WinPDB and stepping through your code. It shows nicely how Python's parser/executor(?) works
def funB(d,c):
return funA(d,c)
print funB(2,3)
def funA(x,y):
return x+y
The above code will return Error. But, the following code is fine ...
def funB(d,c):
return funA(d,c)
def funA(x,y):
return x+y
print funB(2,3)
So, even though you must definitely define the function before any real work is done, it is possible to get away if you don't use the function explicitly. I think this is somewhat similar to prototyping in other languages.. .
For all the people, who despite bad practice want a workaround...
I had a similar problem and solved it like this:
import Configurations as this
'''Configurations.py'''
if __name__ == '__main__':
this.conf01()
'''Test conf'''
def conf01():
print ("working")
So I can change my targeted configuration at the top of the file. The trick is to import the file into itself.
Use multiprocessing module:
from multiprocessing import Process
p1 = Process(target=function_name, args=(arg1, arg2,))
p1.start()

Categories