I'm trying to write name of the current executed function. But it does not work properly.
When I put 'print inspect.stack()[0][3]' after the def func(), it works, but when I try to put this command after the if, it prints nothing.
import inspect
debug = True
def debug():
print inspect.stack()[0][3]
if debug==True:
print "test"
print inspect.stack()[0][3]
debug()
returns 'debug' but it should return
'debug'\n'test'\n'debug'
Where is the problem?
When you define the function:
def debug():
you are loosing the last reference to the previously created variable debug from the global scope. You redefine the debug variable from being a boolean holding True to a function reference. So the condition debug==True is not met (because debug is a function now, not a boolean). And thus only the first print statement works (see an illustrative demo).
This will work as intended, for example:
import inspect
debug = True
def f():
print inspect.stack()[0][3]
if debug==True:
print "test"
print inspect.stack()[0][3]
f()
This is a common mistake in Python, especially from people used to other languages, in which function names are treated in a special way. In Python they are not - after you define a function, you can use its name as any other variable. Which has many advantages, but as seen here sometimes can be confusing.
In python 3 and hight you need to use print () if. It becomes a syntax error and won't print any thing if you don't have the ()
Related
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
I have a question regarding the output from the following code:
def f():
global s
print(s)
s = "That's clear."
print(s)
s = "Python is great!"
f()
print(s)
The output is this:
Python is great!
That's clear.
That's clear.
My question is: Why is it the very last output (i.e. the third output) is also "That's clear" .
How come the third output is not "Python is great!" .
I thought the very last statement from the code (i.e. the print(s)) statement is outside the function f(). So shouldn't print(s) here looks at the s variable that is defined globally? in this case the globally defined variable s would refers to the value "Python is great!", isn't it? Sorry there must be some concepts I have mis-understand. I am very newbie to python. Could someone kindly explain this simple concept.
To see the output you do, the structure of you code has to be:
def f():
global s
print(s) # s outside the function
s = "That's clear." # new global s created
print(s) # print the new s
s = "Python is great!" # s before you call the function/get to s = "That's clear."
f() # f gets called and new global s is created
print(s) # you see the new global s created in the function
Making s global means you see it outside the scope of f, you have already executed the function by the time you reach the last print so now the s points to That's clear.
If you wanted to get the output you expected, you would pass s into the function and not use the global keyword so the s created in f would be accessible only in the scope of the function itself.
def f(s):
print(s)
s = "That's clear."
print(s)
s = "Python is great!"
f(s)
print(s)
This should be a good lesson on why using global is rarely a good idea.
Assuming you have declared the variable s = "Python is great!" globally.
You may not have indented the code properly, the below code:
def f():
global s
print(s)
s = "That's clear."
print(s)
s = "Python is great!"
f()
print(s)
Will give you the output
Python is great!
That's clear.
Python is great!
The code you have written should essentially be giving an infinite recursion and should reach the max recursion depth.
Indentation is very important in python, when you indent the function call f() and the statement print(s), python considers both of these statements to be a part of the function f(). When the statement f() is reached during the first function call, python will automatically call the function again and repeats the whole process. In reality, you will never be able to reach the third print statement.
I have the following code (minus some other operations):
def foobar():
msg=None
if foo:
msg='foo'
else:
msg='bar'
return msg
Is the following better practice for the msg variable?
def foobar():
if foo:
msg='foo'
else:
msg='bar'
return msg
I'm aware that I could simplify the above functions to ternary expressions, however there are operations in each if-else block that I've left out.
Either should be fine but I would probably do:
def foobar():
msg='bar'
if foo:
msg='foo'
return msg
Just for completeness, here are some one-line alternatives to if/else blocks:
msg = 'foo' if foo else 'bar'
msg = foo and 'foo' or 'bar'
msg = ('bar', 'foo')[bool(foo)]
The first of those is definitely the most clear, if you don't like the one-liner I would suggest using your second method or thagorn's answer. The bool() call is only necessary in the last one if foo is not already a bool (or 0/1).
Obviously in your example function you could just return this immediately without even using a msg variable:
def foobar():
return 'foo' if foo else 'bar'
In Python there's no great advantage to initializing before a conditional as in your first example. You just need to be sure that the variable is initialized before it's returned. That assumes (based on your examples) that you're using the "single exit point" paradigm. In some cases in Python it's appropriate, but other times you get cleaner code by exiting early when possible.
def earlyReturn(mycheck):
if not mycheck:
return 'You forgot something.'
# code here if the test passes without needing an extra level of indentation.
I realize that there are some things left out, but if you don't actually need to manipulate msg, I imagine you could just return the intended contents, without ever needing a variable; return 'foo'
I would definitely say that the later is better. There is no recommendation for Python to initialize variables. Therefor it shall be avoided if it's not adding something of value to the code like a fallback value or makes the code more readible, which it does'nt in this case.
Edit: By fallback value I mean the same as thagorn and mikebabcock has suggested.
If what you've shown is all that msg is involved in, then initializing it doesn't do anything for you, and the second solution is better.
If that's the entire logic, why not do:
def foobar():
msg='bar'
if foo:
msg='foo'
return msg
I have a function defined which includes a return statement but no value is handed back. My code is as follows:
def seed(addy):
# urllib2 stuff is here
seed_result = re.search('<td>Results 1 - \d+ of (\d+)',seed_query) # searches for '<td>Results 1 - x of y', captures 'y'
seed_result = seed_result.group(1) # this is 'y' from above
# there's a call to a different function here which works properly
# other stuff going on here pertaining to addy but seed_result still has my string
# now I want to return the seed_result string...
return seed_result
# ... some code outside of the seed function, then I call seed...
seed(addy)
print "Result is %s" % seed_result
I have tried this with and without defining seed_result outside of the function to "initialize" it but this has no impact on the outcome which is that my print statement at the end yields "Result is " - there's no seed_result. I have also wrapped seed_result in parenthesis in the return statement though I believe how I have it is correct. The parens didn't make a difference.
A set up a very basic, yet similar, function in the Python shell and called it as I do here but that works. Not sure what I'm missing.
Thanks for the feedback and guidance.
You're not using the return value (e.g. assigning it to a variable). Try this:
result = seed(addy)
print "Result is %s" % result
Two ways of solving this:
First, the proper, obvious, and easy way is actually using the returned value:
seedresult = seed(addy)
Or you use a global variable (bad style - avoid at any cost):
seedresult = None
def seed(addy):
global seedresult
...
This is caused by None being assigned to seed_result during the execution of your function.
As Jon Skeet identified, you are doing nothing with the return value of your function. You should also address the issues below, though.
In particular, you are doing nothing with the parameter addy, and searching a global variable seed_query. I imagine the behaviour you are seeing is a result of that.
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