Chris Nasr
Chris Nasr

Reputation: 145

Python, how can I initialize a variable during function/method calls

In most interpreted languages (example given in psuedo PHP) I would be able to do something like this

function f($name, &$errors = null) {
    if(something_wrong) {
        if(!is_null($errors) {
            $errors[] = 'some error';
        }
        return false;
    }
}

if(!f('test', $errs = array()) {
    print_r($errs);
}

And get a result like

Array
(
     [0] => some error
)

However when I try this in Python

def f(name, errors = None):
    if something_wrong:
        if errors:
            errors.append('some error')
        return False


if not f('test', errs = []):
    print str(errs)

I get an error

TypeError: f() got an unexpected keyword argument 'errs'

Which makes perfect sense in the context of Python thinking I am trying to set a specific argument, and not create a new variable altogether.

However if I try

if not f('test', (errs = [])):
    print str(errs)

I get

    f('test', (errs = []))
                    ^
 SyntaxError: invalid syntax

Because I think now it assumes I am trying to create a tuple.

Is there any way to keep this code on one line, or do I absolutely have to initialise the variable on it's own before passing it to the function/method? From what I can tell the only solution is this

errs = []
if not f('test', errs):
    print str(errs)

Upvotes: 0

Views: 95

Answers (2)

pBuch
pBuch

Reputation: 1001

"In Python, assignment is a statement, not an expression, and can therefore not be used inside an arbitrary expression."

see http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm

Upvotes: 0

Xiaoqi Chu
Xiaoqi Chu

Reputation: 1557

It should be called as f(name, errors = []) or f(name, []). If you want to init with attribute name, python requires the variable key you given is same with any attribute name you declared in the function definition.

Upvotes: 1

Related Questions