Question

[Solved] Passing expression as argument: keyword can’t be an expression

Here is my actions:

>>> def show(d):
        print d
... 
>>> test = {"result": True}
>>> show(test)
{'result': True}
>>> show(test["info"]="Some info")
  File "<console>", line 1
SyntaxError: keyword can't be an expression

Why can I not pass expression as argument to a function?

Solution #1:

The = sign indicates to Python that this is a keyword parameter, not a positional one. Since the part to the left of the = is an expression test["info"] you get the error.

Respondent: Mark Ransom

Solution #2:

The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct:

if (x = 0) {
    // error handling
}
else {
    // code that only works for nonzero x
}

Source : http://docs.python.org/faq/design.html#why-can-t-i-use-an-assignment-in-an-expression

enter image description here

Respondent: Ashwini Chaudhary

Solution #3:

I think what you want to do is to pass it as a glob type.

show(*test)  

doing this you must match your arg signature so test will have to be defined as

test = {'d' : True}

or show will have to be

def show(result): 
Respondent: Peter Moore

Solution #4:

Because generally it makes no sense. What do you want to get from that? Assignment doesn’t return a value.

Let’s think of a few possibilities:

  • The expression should be passed as a function – you should use lambda, or create an actual function.
  • The expression should return a boolean for success – Python raises exceptions on failure, check for those instead.
  • The expression should give None – there is no value to this.

Either way, what you are trying to do doesn’t make sense.

Respondent: Gareth Latty

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy