functions in PYTHON - python

def other_new_function():
print "HELLO"
print "Start", other_new_function(), "Stop"
The output of this program is:
Start HELLO
None Stop
Why is NONE being showed in the output?

Because you're printing "HELLO", and not returning it.
Because your function does not return anything, it defaults to returning None. Hence, the None that appears.
Change:
def other_new_function():
print "HELLO"
To:
def other_new_function():
return "HELLO"
There's a big difference to returning and printing something from a function:
>>> def func():
... print 1
...
>>> def func2():
... return 1
...
>>> myvar = func()
1 # Printed
>>> myvar2 = func2() # Returned to a variable
>>> print myvar
None
>>> print myvar2
1
Because function 1 prints the value, it never gets returned to a variable.

def other_new_function():
print "HELLO"
returns NoneType (which gets printed as 'None') since you dont explicitly return a value. What you probably want to do is:
def other_new_function():
return "HELLO"

Related

Why do functions print automatically when put in 'if' statement

Why is it that when this code is executed, I would get 'hi'?
Thanks!
def b():
print("hi")
def c():
return True
if b() == 'hi':
print("Done")
You are confusing printing to the console with returning a value. Your function implicitly returns None if you do not return anything from it so it is never equal to 'hi'. Your b() does print - and not return its 'hi'
def b():
print("hi") # maybe uncomment it if you do not want to print it here
return "hi" # fix like this (which makes not much sense but well :o)
def c():
return True
if b() == 'hi':
print("Done")
You can test it like this:
def test():
pass
print(test())
Outputs:
None
Further readings:
about the return statement
about defining functions (read the paragraph below the second fib-CodeBlock example - it tells you about None)
One even more important thing to read: How to debug small programs (#1) - it gives you tips on how to fix code yourself and find errors by debugging.
Essentially what you're doing is saying if b(), which runs the b() function and prints "hi" is equal to "hi", print "done", but since your function prints "hi", rather than returning "hi", it will never equal true.
Try this:
def b():
return "hi"
def c():
return True
if b() == 'hi':
print("Done")

Is there any way to execute a statement before each return statement in python function?

For example i have this piece of code:
def example():
a = 'goodbye'
if True:
print a
return 1
else:
print a
return 0
I would like to know if there is any possible solution to write once "print a" and execute it before each "return" statement automaticaly. So that if I add more return statements I wouldn't need to add anything, but "print a" would execute. Result would look like something:
def example():
a = "goodbye"
""" some code to implement print a """
if True:
return 1
else:
return 0
Each time there is return statement it still would print a.
I tried to google, but don't know how word query, since all results are about returning multiple values.
UPDATE: My question was answered, thanks to all of you.
Although wrapping functions are correct answer, but I have chosen answer by GingerPlusPlus who suggested to use try...finally for simplicity.
try .. finally:
def example():
try:
if True:
return 1
else:
return 0
finally:
print 'goodbye'
>>> example()
goodbye
1
A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. Docs
You can use a context. Initialize it with the value you want to print. Then print when context exit, i.e. upon return.
class PrinterOnContextExit():
def __init__( self, a ): self.a = a
def __enter__( self ): pass
def __exit__( self, exc_type, exc_value, traceback ): print( self.a )
def example():
a = 'goodbye'
with PrinterOnContextExit( a ):
if True:
return 1
else:
return 0
Note that you cannot print the returned value this way. If you ever wanted to print the returned value, then you should use a decorator.
class PrintOnReturn():
def __init__( self, a ): self.a = a
def __call__( self, func ): return lambda *args, **kwargs: self.callFunc( func, *args, **kwargs )
def callFunc( self, func, *args, **kwargs ): r = func( *args, **kwargs ); print( self.a, r ); return r
#PrintOnReturn( "hello" )
def example():
if True:
return 1
else:
return 0
This will print whatever string you passed to the decorator, followed by the value returned from the decorated function. Here hello 1.
Code:
def example():
a = 'goodbye'
print a
if True:
return 1
else:
return 0
If you print a before if else then it will print value every time you call the function.
You could also use a decorator, if it suits your case:
>>> def decorator(text):
... def wrapped(func):
... def inner(*args, **kwargs):
... result = func(*args, **kwargs)
... print text
... return result
... return inner
... return wrapped
...
>>> #decorator('goodbye')
... def example():
... return True
...
>>> example()
goodbye
>>> True
Decorator will allow you to print any text after the decorated function was called. Or before.
Create a value returnval
returnval = 0 #default value
testval = 0 # Code to set up if
# code to set various values of testval
if testval == 0:
returnval = 1
elif testval == 5:
returnval = 2
else:
returnval = 10
print a
return returnval
Def example():
a = 'goodbye'
if True:
return 1,str(a)
else:
return 0,str(a)
print example()
Thats the only way...I dont think there is a way to avoid typing what you want to be printed...sorry mate! expect if you type a function type the thinks you
An easier alternative as i've also posted here for a similar topic:
def master_example():
a = []
def example():
a.append('goodbye')
if True:
return 1
else:
return 0
example()
print a[0]

How to return value from exec in function?

I try:
def test(w,sli):
s = "'{0}'{1}".format(w,sli)
exec(s)
return s
print test("TEST12344","[:2]")
its return 'TEST12344'[:2]
How to return value from exec in function
Think of running the following code.
code = """
def func():
print("std out")
return "expr out"
func()
"""
On Python Console
If you run func() on the python console, the output would be something like:
>>> def func():
... print("std out")
... return "expr out"
...
>>> func()
std out
'expr out'
With exec
>>> exec(code)
std out
>>> print(exec(code))
std out
None
As you can see, the return is None.
With eval
>>> eval(code)
will produce Error.
So I Made My exec_with_return()
import ast
import copy
def convertExpr2Expression(Expr):
Expr.lineno = 0
Expr.col_offset = 0
result = ast.Expression(Expr.value, lineno=0, col_offset = 0)
return result
def exec_with_return(code):
code_ast = ast.parse(code)
init_ast = copy.deepcopy(code_ast)
init_ast.body = code_ast.body[:-1]
last_ast = copy.deepcopy(code_ast)
last_ast.body = code_ast.body[-1:]
exec(compile(init_ast, "<ast>", "exec"), globals())
if type(last_ast.body[0]) == ast.Expr:
return eval(compile(convertExpr2Expression(last_ast.body[0]), "<ast>", "eval"),globals())
else:
exec(compile(last_ast, "<ast>", "exec"),globals())
exec_with_return(code)
exec() doesn't just evaluate expressions, it executes code. You would have to save a reference within the exec() call.
def test(w, sli):
exec('s = "{}"{}'.format(w, sli))
return s
If you just want to evaluate an expression, use eval(), and save a reference to the returned value:
def test(w,sli):
s = "'{0}'{1}".format(w,sli)
s = eval(s)
return s
However, I would recommend avoiding exec() and eval() in any real code whenever possible. If you use it, make sure you have a very good reason to do so.
My findings in Python 3.8 in 2020
in Eval Logic :
a="1+99"
a=eval(a)
print(a) # output: 100
in exec logic
exec ("a=33+110")
print(a) #output 143

accessing python dict with function values

I am trying to make a menu of options in python where if the user selects a number a different function is executed:
def options(x):
return {
1: f1(),
2: f2()
}[x]
def f1():
print "hi"
def f2():
print "bye"
However, well I call
options(1)
I get:
hi
bye
and same when I call options(2)
What is going on?
You are invoking the functions instead of assiging them against the keys
def f1():
print "hi"
def f2():
print "bye"
functions = {1: f1, 2: f2} # dict of functions (Note: no parenthesis)
def options(x):
return functions[x]() # Get the function against the index and invoke it
options(1)
# hi
options(2)
# bye
Your dictionary is built with the return values of the functions; don't call the function until after picking it from the dict:
def options(x):
return {
1: f1,
2: f2
}[x]()
Now you are storing just a reference to the functions in the dictionary, and call the selected function after retrieving it.
Demo:
>>> def f1():
... print "hi"
...
>>> def f2():
... print "bye"
...
>>> def options(x):
... return {
... 1: f1,
... 2: f2
... }[x]()
...
>>> options(1)
hi
>>> options(2)
bye
Replace print with return and return with, then it will work. Or use thefourtheye version.
The problem is that you call the functions (with ()) while you are building the dictionary. Leave the parens off and apply them later only after getting the value from the dictionary:
def options(x):
return {
1: f1,
2: f2
}[x]()

Decorator to log function execution line by line

I'm working on a script that takes a few minutes to run, and would like to provide some output to the user about its progress. Unfortunately i'm exceedingly lazy. what I'd like to do is write a function without the logging, and then apply a decorator to it which steps through the function and prints each line before executing that line. Basically what I'm looking for is a loggingdecorator such that:
>>> #loggingdecorator
... def myfunction():
... foo()
... bar()
... baz()
>>> myfunction()
Starting myfunction
foo() ... [OK]
bar() ... [OK]
baz() ... [OK]
myfunction Done!
Here's what I've tried so far:
import sys
def logging_tracer(frame, event, arg):
def local_tracer(local_frame, event, arg):
if frame is local_frame:
print frame.f_code.co_name, event, arg
print frame.f_code.co_name, event, arg
return local_tracer
def loggingdecorator(func):
def _wrapper():
old_trace_function = sys.gettrace()
sys.settrace(logging_tracer)
try:
result = func()
except:
raise
else:
return result
finally:
sys.settrace(old_trace_function)
return _wrapper
Unfortunately, this prints a bit too much; it follows function calls and prints them out, line by line as well (well, this doesn't actually print the source line, existing answers using inspect, combined with stuff on the frame object in the trace function would do it), but I'm a bit stumped as to how the logging_tracer unless the function in question is actually decorated.
So here's what I came up with. #Corley Brigman's comment got me started in the right direction. This is a bit hackey, sys.gettrace/settrace are rather promenently documented as "CPython implementation details", and so this solution should not be expected to work in other implementations. That said, it seems to work out pretty well. The tracing functionality in cpython does not provide any notification of "line finished executing", so the [ok] from my question doesn't really make any sense.
Fixing the recursive tracing issue is just a simple matter of keeping a cache of the functions that were decorated, and then only produce output if the frame being traced is from a function that was decorated.
import inspect
import sys
def logging_tracer(frame, event, arg):
lines, firstline = inspect.getsourcelines(frame)
def local_tracer(local_frame, event, arg):
if event == 'line' and frame is local_frame:
print event, frame.f_lineno,'\t', lines[frame.f_lineno - firstline]
#print event, lines[frame.f_lineno - firstline]
#print frame.f_code.co_name, frame.f_lineno, event, arg
if frame.f_code in LOG_THESE_FUNCTIONS:
print event, frame.f_lineno,'\t', lines[frame.f_lineno - firstline + (event == 'call')]
#print frame.f_code.co_name, event, arg
return local_tracer
else:
return None
LOG_THESE_FUNCTIONS = set()
def loggingdecorator(func):
LOG_THESE_FUNCTIONS.add(func.func_code)
def _wrapper():
old_trace_function = sys.gettrace()
sys.settrace(logging_tracer)
try:
result = func()
except:
raise
else:
return result
finally:
sys.settrace(old_trace_function)
return _wrapper
Here's an ugly example that works if there's only one indentation level:
import inspect
def myDec(func):
temp = list(inspect.getsourcelines(func)[0])
temp.append(' print("{} Done!")\n'.format(func.__name__))
for index in range(len(temp)-2, 0, -1):
temp.insert(index+1, " print('''{}...[OK]''')\n".format(temp[index].strip().rstrip("\n")))
temp.insert(1, ' print("Starting {}")\n'.format(func.__name__))
temp = "".join(temp)
exec(temp)
return locals()[func.__name__]
def foo():
a = 4+5
list_int = range(100)
foo = myDec(foo)
foo()
Really ugly though...
You can do something like this:
>>> class loggingdecorator:
... def __init__(self, func):
... self.func = func
... def __call__(self):
... print "Entering", self.func.__name__
... self.func()
... print "Exited", self.func.__name__
...
Then with each of your functions:
>>> #loggingdecorator
... def func1():
... print "Hello from func1(), how are you doing?"
...
>>> #loggingdecorator
... def func2():
... print "Hello from func2(), Whaddup Dawg...?"
...
>>> func1()
Entering func1
Hello from func1(), how are you doing?
Exited func1
>>> func2()
Entering func2
Hello from func2(), Whaddup Dawg...?
Exited func2
Found the example from this page

Categories

Resources