is Python return always necessary [duplicate] - python

This question already has answers here:
return, return None, and no return at all?
(5 answers)
Closed 7 years ago.
I just stumbled across several python programs written by different people and I noticed that every function had a return at the end of it
def function01():
# function
# events
# here
return
I was wondering if it's good python programming practice to include return at the end of functions even if it is not returning anything (purely as a way of ending the function)
Or is it not needed and nothing different will happen in the background?

No, it is not necessary. The function returns after the last line. There is no difference between a simple return and no return.
def foo():
pass
def bar():
pass
return
f = foo()
print(f)
b = bar()
print(b)
Output:
None
None

Related

"return" and "return None" behavior difference in generator [duplicate]

This question already has answers here:
Return in generator together with yield
(2 answers)
Why can't I use yield with return?
(5 answers)
Closed 3 years ago.
Simple method with just return keyword returns a None
def abc():
return
print(abc())
Output: None
Similarly,
def abc():
return None
print(abc())
Output: None
However if we use this in generator
def abc():
yield 1
return None
print(abc())
it gives
SyntaxError: 'return' with argument inside generator
where as
def abc():
yield 1
return
print(abc())
gives
<generator object abc at 0x7f97d7052b40>
Why do we have this difference in behavior?
A bare return is useful to break out early from a generator.
Meanwhile return None is just a special case of return <a value>, and before yield from (PEP 380) there was no support or use case for returning a value from a generator. So it was forbidden in order to leave the design space open: by forbidding returning values in generators, Python's designers made it possible to allow it later with new semantics as that would not break existing code.
Had they allowed a return value without doing anything with it, there was a risk userland code would break. That's why from a forward-compatibility perspective it's often better to restrict APIs as much as possible, everything you leave open users will take advantage of, and it becomes risky to change.

Understanding how does a decorator really work [duplicate]

This question already has answers here:
How do I make function decorators and chain them together?
(20 answers)
Closed 4 years ago.
I'm starting studying decorators and I already hit an obstacle. First here is my code.
def deco (f):
def coucou():
print("this is function{}".format(f))
return f()
return coucou
#deco
def salut():
print("salut")
def hi():
return salut()
I will try to explain my problem as well as I can with my bad English. If I understand it this is how things should happen: I execute my hi() function which returns salut() and because salut is modified by the decorator coucou will be executed and coucou returns ....... salut(), what i mean is that I expect an infinite loop but that doesn't happen and I don't understand why. Can anyone explain practically how decorators work?
The f in coucou is the undecorated (original) version of salut.

passing object to object [duplicate]

This question already has answers here:
Can you explain closures (as they relate to Python)?
(13 answers)
Closed 6 years ago.
I am trying to understand the background of why the following works:
def part_string(items):
if len(items) == 1:
item = items[0]
def g(obj):
return obj[item]
else:
def g(obj):
return tuple(obj[item] for item in items)
return g
my_indexes = (2,1)
my_string = 'ABCDEFG'
function_instance = part_string(my_indexes)
print(function_instance(my_string))
# also works: print(part_string(my_indexes)(my_string))
how come I can pass my_string to function_instance object even though I already passed my_indexes attributes to part_string() when creating function_instance? why Python accepts my_string implicitly?
I guess it has something to do with the following, so more questions here:
what is obj in g(obj)? can this be something other e.g. g(stuff) (like with self which is just a convention)?
what if I want to pass 2 objects to function_instance? how do I refer to them in g(obj)?
Can You recommend some reading on this?
What you're encountering is a closure.
When you write part_string(my_indexes) you're creating a new function, and upon calling it, you use the old variables you gave to part_string together with the new variables given to function_instance.
You may name the inner function whatever you want, and there is no convention. (obj is used in here but it can be pie. There are no conventions for this except func for function closures (decorators).
If you wish to pass two variables to the function, you may define two variables to the g(obj) function:
def g(var1, var2):
...
Here's some more info regarding closures in python.

Why isn't there any output when I call out a function I define before? [duplicate]

This question already has an answer here:
Code shows results when run interactively, but not when run from a shell
(1 answer)
Closed 8 years ago.
I type some code like this:
def cod():
return 4
cod()
But I get no output from it. Isn't it supposed to output a "4" when I call the function "cod()" ?
When you return something in your function, you have to use it with print function, otherwise you can't display it.
def cod():
return 4
print (cod())
If you don't return something and using print, then you can use it same as in your question.
def cod():
print (4)
cod()
Note that if you use print at second one, you get this output;
>>>
4
None
>>>
That's because default return is None and you are not return something from your function, just printing it. Better using return.
return does not print any value you need to explicitly tell your function to do so
print(cod()) #python3
or
print cod() #python2
Python only automatically print the value of an expression in the interactive interpreter.
if you want to print a function value
you should modify your code to be
def cod():
return 4
print cod()

What does an empty return in Python mean? [duplicate]

This question already has answers here:
return, return None, and no return at all?
(5 answers)
Closed 8 years ago.
When looking through Python code on GitHub, I've seen several examples of a return with no value. For example:
if hasattr(self, 'moved_away'):
return
# and here code continues
What does the empty return mean?
It means it will return None. You could remove the return and it would still return None because all functions that don't specify a return value in python will by default return None.
In this particular case it means the code will go no further if the object has the attribute 'moved_away', without the return any code below would be evaluated even if the if statement evaluated to True.
So you can think of it as being similar to a break statement in a loop when you have a condition you want to exit the loop on, without the break the code would continue to be evaluated.
if hasattr(self, 'moved_away'): # if this is True we return/end the function
return
# if previous statement was False we start executing code from here
return exits the current function.
So, here it will stop the execution & return None.

Categories