Python lambda no return value

Is there a way to return literally nothing in python?

I’m learning python and I was just wondering if I there was a way to write a code that does something like:

def f(x): if x>1: return(x) else: # don't return anything 

I’m asking about the else part of the code. I need to not return anything if x

When you just leave the function it is returning None , only way to avoid it is to throw exception or have non-terminating function.

@Kirca: You haven’t said why None is unacceptable, but it’s probably due to a misconception. There’s no way to end a function without either returning a value or raising an exception.

What do you want var to be bound to when you write var = foo() and the function is «returning literally nothing»? You have to raise and add error handling to the caller.

13 Answers 13

There is no such thing as «returning nothing» in Python. Every function returns some value (unless it raises an exception). If no explicit return statement is used, Python treats it as returning None .

So, you need to think about what is most appropriate for your function. Either you should return None (or some other sentinel value) and add appropriate logic to your calling code to detect this, or you should raise an exception (which the calling code can catch, if it wants to).

+1 Although, could technically just «not return» (instead of return None ) and it would be just as valid .. although it would offend my sensibilities.

Читайте также:  Python math округление до сотых

None , nothing , null , and nil are used in programming languages to represent nothingness: nshipster.com/nil. Meaning that returning None is the correct answer.

To literally return ‘nothing’ use pass , which basically returns the value None if put in a function(Functions must return a value, so why not ‘nothing’). You can do this explicitly and return None yourself though.

if x>1: return(x) else: return None 

«OP said returning None is not acceptable» True, but that makes no sense, and OP hasn’t explained what he meant.

pass doesn’t «basically return the value None «; it literally doesn’t do anything at all. The None return in that code example happens because control flow reaches the end of the function. else: pass is equivalent to omitting the else block in every case, i.e. even if there is more code after the complete if block.

def function(x): try: x = x+1 return (x) except: return ('') 

so this is the only thing that made sense on all these webpages for some reason. I don’t really even want to return an empty string, but it works because I do not want to see None printed right now.

«but it works because I do not want to see None printed right now.» Then there is an XY problem here, and the original question did not properly clarify the problem.

There’s nothing like returning nothing but what you are trying to do can be done by using an empty return statement. It returns a None .

You can see an example below:

if 'account' in command: account() def account(): talkToMe('We need to verify your identity for this. Please cooperate.') talkToMe('May I know your account number please?') acc_number = myCommand() talkToMe('you said your account number is '+acc_number+'. Is it right?') confirmation = myCommand() if confirmation!='yes' or 'correct' or 'yeah': talkToMe('Let\'s try again!') account() else: talkToMe('please wait!') return 

This will return nothing to calling function but will stop the execution and reach to the calling function.

if confirmation!=’yes’ or ‘correct’ or ‘yeah’: does not do what you want it to do, and calling account() recursively to «restart» the function is ill-conceived.

@KarlKnechtel This is a snippet from a project I was working on. The code is correct with respect to the project and it answers the question asked.

You can do something like this:

>>> def f(x): . return x if x>1 else None . >>> f(1),f(2) (None, 2) 

It will appear to ‘return nothing’:

But even the alternative returns None:

>>> def f2(x): . if x>1: return x . >>> f2(1),f2(2) (None, 2) 
>>> def f2(x): . if x>1: . return x . else: . pass . >>> f2(1),f2(2) (None, 2) 

So they are functionally the same no matter how you write it.

As mentioned above by others, it will always return None in your case. However you can replace it with white space if you don’t want to return None type

def test(x): if x >1: return(x) else: return print('')

Just to add to all the answers, the only actual way to not return a function is to raise an exception. At least, as long as the program needs to run even after not returning anything.

def f(x): if x>1: return x raise Exception 

(Note that I didn’t use an else block to raise the Exception since it would have already returned the value if the condition was satisfied. You could, however, do this in an else block, too)

num1 = f(2) # 2 num2 = f(0) # Unbound; and error raised 

Now this can be useful if you want to also keep returning None an option for some conditions, and not returning anything for some other conditions:

def f(x): if x > 0: return x elif x == 0: return None # pass raise Exception >>> num1 = f(1) # 1 >>> num2 = f(0) # None >>> num3 = f(-1) # Unbound; and error raised 

If you don’t want the program to exit and show an error, you can make it catch the exception outside of the function:

This way, if at all f(0) raises an exception (which it would) it will be caught be the except block and you can happily continue the program, being rest assured that num is not None , but simply unbound.

The only other way to not return anything is probably to simply exit the program, which is what exit() and quit() do. When I check the return type for exit() and quit() in my code editor, it shows me NoReturn , which is different from when it shows None for a regular function 🙂

Источник

Getting a return value from Lambda python

Which as I understand is that i send in [‘a’.’a’] into lambda d from which I would like a return value similar to True Am I misunderstanding something basic? EDIT: The calling itself is not the problem but the return value being:

instead of a value (i.e. True) and I’m not sure if that is the fault of my calling or the function itself The call is done with a «help function»

calling(input) return rule_defs[input[0]](input) 

«when I try to run it. « How exactly are you running it? I’m guessing (‘and’, ‘a’, ‘a’) are your arguments, but that’s not really sufficient to replicate your problem. MCVE please.

. what? Why are you nesting lambda s? What is it supposed to be doing? I would strongly suggest using a standlone function for this, so you can more easily test and document its behaviour.

You have two functions, the first which appears to take a list of rules and returns your function that you call with three arguments. there’s a whole lot here that you’re not showing us. like how exactly you call this thing.

@jonrshape The reason for nesting the lamdas was so that I «easily» could use a recursive function to go through a more nested and/or (or more advanced) functions e.g. (‘and’, (‘or’ (‘something’, ‘a’, ‘b’)))

@Kevin I pretty much just have a function which directly tries to call the rule_defs with the input >helpfunction(r) > return rule_defs[r[0]](r) with the r being ((‘=’, ‘a’, ‘a’))

3 Answers 3

Firstly, if you want your inner function to produce a tuple, you should also add another ‘(‘ after starting the inner lambda and close it just before.

Or if you were doing it correctly, and outer lambda intended to return a tuple of (lambda, list) , then to call the inner lambda use rule_defs[‘and’]()[0]()

When defining lambda within a lambda , you have to call first lambda with () and then again the second lambda with () .

So in your case , you would call your function with —

Or you can assign it to a variable and then call that variable with the double paranthesis.

>>> rule_defs = < 'and': lambda r: (lambda d ,r1: print(d))>>>> rule_defs['and'](1)(2,3) 2 

Источник

The lambda function does not return value

The lambda function does not return the desired value to me I sent lambda x: x * 3.87 and I get ₪ 50 The problem is that x does not get the value 50 so lambda does not work I would love to help how I get the value ₪ 193.50. the problem is here c(‘convert’)(lambda x: x*3.87, ‘₪’)

def make_currency(val, sym): def dispatch(message): if message == 'get_value': def get_value(msg): if msg == 'amount': return val elif msg == 'symbol': return sym return get_value if message == 'set_value' or message == 'convert': def set_value(msg, value): nonlocal val nonlocal sym if msg == 'amount': val = value elif msg == 'symbol'or message == 'convert': sym = value return set_value return ''.format(sym,val) return dispatch c = make_currency(10.50,'$') print(c('get_value')('amount')) print(c('get_value')('symbol')) c('set_value')('amount',50) print(c('get_value')('amount')) print(c('str')) c('convert')(lambda x: x*3.87, '₪') print(c('str')) 

Just a heads up that you should seriously consider looking at class es. Selecting actions via messages corresponds to a class ‘ methods and storing values via closures/ nonlocal corresponds to a class ‘ attributes.

Either way, the msg of set_value is only used in the comparison against ‘amount’ and ‘symbol’ – why do you expect it to be called with the value ?

1 Answer 1

You’re missing a branch where you handle the lambda .

A lambda is just an anonymous one line function so you need to call it like you would any other function.

def make_currency(val, sym): def dispatch(message): if message == 'get_value': def get_value(msg): if msg == 'amount': return val elif msg == 'symbol': return sym return get_value if message == 'set_value' or message == 'convert': def set_value(msg, value): nonlocal val nonlocal sym if msg == 'amount': val = value elif msg == 'symbol' or message == 'convert': sym = value # this will handle the lambda assigned to msg if message == 'convert': val = msg(val) return set_value return ''.format(sym,val) return dispatch c = make_currency(10.50,'$') print(c('get_value')('amount')) print(c('get_value')('symbol')) c('set_value')('amount',50) print(c('get_value')('amount')) print(c('str')) c('convert')(lambda x: x*3.87, '₪') print(c('str')) 

That being said, you really should be using classes for this as most people would find the closures in this context extremely confusing.

Источник

Оцените статью