0

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)

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't see how this helps me, in fact you've completely removed the initialization of errs, so there's no way I can access it after the function call is completed.
0

"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

1 Comment

Thank you pBuch, that's what I was looking for. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.