Python: pass statement in lambda form - python

A Python newbie question, why is this syntax invalid: lambda: pass, while this: def f(): pass is correct?
Thanks for your insight.

lambdas can only contain expressions - basically, something that can appear on the right-hand side of an assignment statement. pass is not an expression - it doesn't evaluate to a value, and a = pass is never legal.
Another way of thinking about it is, because lambdas implicitly return the result of their body, lambda: pass is actually equivalent to:
def f():
return pass
Which doesn't make sense. If you really do need a no-op lambda for some reason, do lambda: None instead.

That is an error because after the colon you have to put the return value, so:
lambda: pass
is equal to:
def f():
return pass
that indeed makes no sense and produces a SyntaxError as well.

The return value of a function without a return statement is None. You can see this from the simple pass function that is defined in the OP:
>>> def f():
... pass
...
>>> print f()
None
If you are looking for a lambda function that is equivalent to this "no-op" function, then you can use:
lambda: None
For example:
>>> f = lambda: None
>>> print f()
None

If you want to use a lambda you could rely on the Ellipsis literal ....
Your lambda would become lambda: ....
The Ellipsis literal is often used instead of pass.

Related

2's complement function in python [duplicate]

I tried writing this code:
def smaller(x, y):
if x > y:
print(y)
else:
print(x)
print(smaller(2, 3))
I got this result:
>>>
2
None
Where did the None come from? What does it mean?
See also
The accepted answer explains the importance of returning a value from the function, rather than printing it. For more information, see What is the purpose of the return statement? How is it different from printing?.
To understand the None result itself, see What is a 'NoneType' object?.
If you are printing inside the function in order to see multiple values, it may be better to instead collect those values so that they can be printed by the calling code. For details, see How can I use `return` to get back multiple values from a loop? Can I put them in a list?.
It's the return value of the function, which you print out. If there is no return statement (or just a return without an argument), an implicit return None is added to the end of a function.
You probably want to return the values in the function instead of printing them:
def jiskya(x, y):
if x > y:
return y
else:
return x
print(jiskya(2, 3))
Ok, to start off when you do this:
print(jiskya(2, 3))
You getting something pretty much equivalent to this:
print(print(2))
So, what is going on? The print(2) is printing out 2, and returns None which is printed by the outer call. Straightforward enough.
Now look at this:
def hello():
return 2
If you do:
print(hello())
You get 2 because if you print out a function you get whatever the return value is. (The return value is denoted by the return someVariable.
Now even though print doesn't have parenthesis like most functions, it is a function just a little special in that respect. What does print return? Nothing. So when you print print someVariable, you will get None as the second part because the return value of print is None.
So as others have stated:
def jiskya(x, y):
if x > y:
print(y)
else:
print(x)
Should be re-written:
def jiskya(x, y):
if x > y:
return y
else:
return x
Where did the 'None' come from?
The function.
And what is it?
It's what the function returned.
In Python, every function returns something. It could "be multiple things" using a tuple, or it could "be nothing" using None, but it must return something. This is how we deal with the fact that there is no way to specify a return type (which would make no sense since you don't specify types for anything else). When interpreted as a string for printing, None is replaced with the string "None".
None is a special object that is supposed to represent the absence of any real thing. Its type is NoneType (it is an instance of that class). Whenever you don't explicitly return anything, you implicitly return None.
You wrote the function to print one of the two values x or y, but not to return anything. So None was returned. Then you asked Python to print the result of calling the function. So it called the function (printing one of the values), then printed the return value, which was None, as the text "None".
You are doing two prints, the first one in the corpus of your function and the second one is printing the result of the function, which as actually None.
You should rather do something like this:
def yourfunction(x, y):
if x > y:
return y
else:
return x
Then,
>>> print yourfunction(2, 3)
2
Ya, basically you are using print statements in your function as a way to return information. You shouldn't do this. Print is NOT the same as a return statement. If you simply want your function to give your answer without the none, just type jiskya(2, 3) instead. You will see what the function throws out because you have print statements in the function. If instead you typed "return" in your function, it wouldn't give you anything without the "print" preceding the function call.
The problem is you wrote print jiskya(2,3). You're passing the return value of jiskya to the print function. jiskya itself prints x or y, which is why you see the 2. But then the print in the print jiskya(2, 3) statement itself executes with no argument.
To the interpreter, this is a simplification of what happens:
print jiskya(2,3)
>> Executing jiskya with arguments 2, 3
>> jiskya evaulates `print x`
>> 2 is printed
>> Function jiskya exits with no return value
print None
>> None is printed
Consider following examples:
Function without return statement
Print() function type is none type..
def test1():
print("code...!!!")
type(test1())
Output: code...!!!
NoneType
Function with return statement
Returning variable 'a' which holds print() function, that's why type() returns data type of print function which is NoneType, not the data type of what's inside the print funcion:
def test1():
a= print("code...!!!")
return a
type(test1())
Output: code...!!!
NoneType
Here function returning data type of variable 'a' which holds a string in it.
def test1():
a = "First code...!!!"
return a
type(test1())
Output: str

pass a function name as argument and then check correctness

I'm aware that I cann pass a function name as an argument to another function i.e
def fun_passed(a,b):
#do something
def main_fun(arg,fun_passed):
#do something
#call main_fun
first_fun =fun_passed
main_fun(1,first_fun)
Inside main_fun how can I make some checks.
For example, Based on the function i passed i want to set a variable
def main_fun(1,fun_passed):
if fun_passed==first_fun:
i=1
else:
i=10
I can't simply use == because i think that comparison doesn't make sense.
Thanks
You can compare functions for equality, but it's not going to check if the two functions do the exact same thing. Such a check is, in general, undecidable in the technical sense.
Instead, f == g simply returns true if both f and g return to the same underlying object (i.e., it's the same as f is g). This means that something as simple as (lambda x: x) == (lambda x: x) evaluates as False.
You should use the is keyword:
def fct_a(a,b):
#do something
pass
def fct_b(a,b):
#do something
pass
def main_fun(fct):
if fct is fct_a:
print("fct is 'fct_a'")
else:
print("fct is not 'fct_a'")
main_fun(fct_a) # >> fct is 'fun_passed'
main_fun(fct_b) # >> fct is not 'fun_passed'
For more about the differences between is and ==, see there
If you are dealing with functions, not a lambda, the function object has a variable __name__ which shows the exact name of the original function. Here a simple example:
>>> def x():
... return 0;
...
>>> type(x)
<type 'function'>
>>> x.__name__
'x'
>>> y=x
>>> y.__name__
'x'
So in your case, it will be something like this
if fun_passed.__name__=="first_fun":

What to do to remove None [duplicate]

I tried writing this code:
def smaller(x, y):
if x > y:
print(y)
else:
print(x)
print(smaller(2, 3))
I got this result:
>>>
2
None
Where did the None come from? What does it mean?
See also
The accepted answer explains the importance of returning a value from the function, rather than printing it. For more information, see What is the purpose of the return statement? How is it different from printing?.
To understand the None result itself, see What is a 'NoneType' object?.
If you are printing inside the function in order to see multiple values, it may be better to instead collect those values so that they can be printed by the calling code. For details, see How can I use `return` to get back multiple values from a loop? Can I put them in a list?.
It's the return value of the function, which you print out. If there is no return statement (or just a return without an argument), an implicit return None is added to the end of a function.
You probably want to return the values in the function instead of printing them:
def jiskya(x, y):
if x > y:
return y
else:
return x
print(jiskya(2, 3))
Ok, to start off when you do this:
print(jiskya(2, 3))
You getting something pretty much equivalent to this:
print(print(2))
So, what is going on? The print(2) is printing out 2, and returns None which is printed by the outer call. Straightforward enough.
Now look at this:
def hello():
return 2
If you do:
print(hello())
You get 2 because if you print out a function you get whatever the return value is. (The return value is denoted by the return someVariable.
Now even though print doesn't have parenthesis like most functions, it is a function just a little special in that respect. What does print return? Nothing. So when you print print someVariable, you will get None as the second part because the return value of print is None.
So as others have stated:
def jiskya(x, y):
if x > y:
print(y)
else:
print(x)
Should be re-written:
def jiskya(x, y):
if x > y:
return y
else:
return x
Where did the 'None' come from?
The function.
And what is it?
It's what the function returned.
In Python, every function returns something. It could "be multiple things" using a tuple, or it could "be nothing" using None, but it must return something. This is how we deal with the fact that there is no way to specify a return type (which would make no sense since you don't specify types for anything else). When interpreted as a string for printing, None is replaced with the string "None".
None is a special object that is supposed to represent the absence of any real thing. Its type is NoneType (it is an instance of that class). Whenever you don't explicitly return anything, you implicitly return None.
You wrote the function to print one of the two values x or y, but not to return anything. So None was returned. Then you asked Python to print the result of calling the function. So it called the function (printing one of the values), then printed the return value, which was None, as the text "None".
You are doing two prints, the first one in the corpus of your function and the second one is printing the result of the function, which as actually None.
You should rather do something like this:
def yourfunction(x, y):
if x > y:
return y
else:
return x
Then,
>>> print yourfunction(2, 3)
2
Ya, basically you are using print statements in your function as a way to return information. You shouldn't do this. Print is NOT the same as a return statement. If you simply want your function to give your answer without the none, just type jiskya(2, 3) instead. You will see what the function throws out because you have print statements in the function. If instead you typed "return" in your function, it wouldn't give you anything without the "print" preceding the function call.
The problem is you wrote print jiskya(2,3). You're passing the return value of jiskya to the print function. jiskya itself prints x or y, which is why you see the 2. But then the print in the print jiskya(2, 3) statement itself executes with no argument.
To the interpreter, this is a simplification of what happens:
print jiskya(2,3)
>> Executing jiskya with arguments 2, 3
>> jiskya evaulates `print x`
>> 2 is printed
>> Function jiskya exits with no return value
print None
>> None is printed
Consider following examples:
Function without return statement
Print() function type is none type..
def test1():
print("code...!!!")
type(test1())
Output: code...!!!
NoneType
Function with return statement
Returning variable 'a' which holds print() function, that's why type() returns data type of print function which is NoneType, not the data type of what's inside the print funcion:
def test1():
a= print("code...!!!")
return a
type(test1())
Output: code...!!!
NoneType
Here function returning data type of variable 'a' which holds a string in it.
def test1():
a = "First code...!!!"
return a
type(test1())
Output: str

'return outside of function' error with correct indentation?

in python, it comes out with 'return outside of function', I check the indentation is nothing wrong. any clue on that?
dict={1:10,2:20,3:30}
for a,b in dict.items():
if b==30:
return a
There's no function, so you cannot use return. You may wrap the code in def:
d={1:10,2:20,3:30}
def return_30(d):
for a,b in d.items():
if b==30:
return a
Also I renamed dict to d, because dict is a name of the type, and when you redefine it you lose access to original dict.
The for loop, isn't a function.
A function in python is DEFined using the def keyword as in:
def function():
print(1+2) # Im inside the function, return keyword here is valid
# I'm outside the function.
for x in range(10):
print(x)
#This is not a function, return keyword here is invalid.

Python - Passing a function into another function [duplicate]

This question already has answers here:
Python function as a function argument?
(10 answers)
Closed last month.
I am solving a puzzle using python and depending on which puzzle I am solving I will have to use a special set of rules. How can I pass a function into another function in Python?
Example
def Game(listA, listB, rules):
if rules == True:
do...
else:
do...
def Rule1(v):
if "variable_name1" in v:
return False
elif "variable_name2" in v:
return False
else:
return True
def Rule2(v):
if "variable_name3" and "variable_name4" in v:
return False
elif "variable_name4" and variable_name1 in v:
return False
else:
return True
This is just a pseudo code and therefore not specific but I get the code to compile but I need to know how to call the function Game and whether it's correctly defined since rules will be switched for either Rule1(v) or Rule2(v).
Just pass it in like any other parameter:
def a(x):
return "a(%s)" % (x,)
def b(f,x):
return f(x)
print b(a,10)
Treat function as variable in your program so you can just pass them to other functions easily:
def test ():
print "test was invoked"
def invoker(func):
func()
invoker(test) # prints test was invoked
For passing both a function, and any arguments to the function:
from typing import Callable
def looper(fn: Callable, n:int, *args, **kwargs):
"""
Call a function `n` times
Parameters
----------
fn: Callable
Function to be called.
n: int
Number of times to call `func`.
*args
Positional arguments to be passed to `func`.
**kwargs
Keyword arguments to be passed to `func`.
Example
-------
>>> def foo(a:Union[float, int], b:Union[float, int]):
... '''The function to pass'''
... print(a+b)
>>> looper(foo, 3, 2, b=4)
6
6
6
"""
for i in range(n):
fn(*args, **kwargs)
Depending on what you are doing, it could make sense to define a decorator, or perhaps use functools.partial.
Just pass it in, like this:
Game(list_a, list_b, Rule1)
and then your Game function could look something like this (still pseudocode):
def Game(listA, listB, rules=None):
if rules:
# do something useful
# ...
result = rules(variable) # this is how you can call your rule
else:
# do something useful without rules
A function name can become a variable name (and thus be passed as an argument) by dropping the parentheses. A variable name can become a function name by adding the parentheses.
In your example, equate the variable rules to one of your functions, leaving off the parentheses and the mention of the argument. Then in your game() function, invoke rules( v ) with the parentheses and the v parameter.
if puzzle == type1:
rules = Rule1
else:
rules = Rule2
def Game(listA, listB, rules):
if rules( v ) == True:
do...
else:
do...

Categories

Resources