Skip to content

Stumbled on a strange Walrus operator/assignment expression behavior #138583

@123swk123

Description

@123swk123

Bug report

Bug description:

A nice elegant way to check and assign the variable for None

# Typical behavior of assignment expression in IF-Statement
>>> i=None
>>> if j:=i:
...     print(f'Valid: {j}')
... else:
...     j=100
...     print(f'Not Valid: {j}')
Not Valid: 100

>>> i=10
>>> if j:=i:
...     print(f'Valid: {j}')
... else:
...     j=100
...     print(f'Not Valid: {j}')
Valid: 10

Now I am trying the same logic for argument parsing

>>> import argparse
>>> parser = argparse.ArgumentParser(description='Program binary file to one or more device(s)')
>>> parser.add_argument('--ice-id', type=int, required=False, help='Pseudo ICE ID, if not provided then calculated usin
... g chip index')
>>> parser.add_argument('--chip-idx', type=int, action='extend', nargs='*', help='Target chip index')

# invoking with out --ice-id so it should be None
# it's as expected so far.
>>> args=parser.parse_args(['--chip-idx', '0', '1'])
>>> args
Namespace(ice_id=None, chip_idx=[0, 1])

>>> if j:=args.ice_id:
...     print(f'Valid: {j}')
... else:
...     j=100
...     print(f'Not Valid: {j}')
Not Valid: 100

# Now with --ice-id argument, so I expect `Valid: 0` but it outputs `Not Valid: 100`
>>> args=parser.parse_args(['--chip-idx', '0', '1', '--ice-id', '0'])
>>> args
Namespace(ice_id=0, chip_idx=[0, 1])

>>> if j:=args.ice_id:
...     print(f'Valid: {j}')
... else:
...     j=100
...     print(f'Not Valid: {j}')
Not Valid: 100

If I use the parenthesis to be more explicit on my assignment expression, then it works as expected

>>> args
Namespace(ice_id=0, chip_idx=[0, 1])

>>> if (j:=args.ice_id) is not None:
...     print(f'Valid: {j}')
... else:
...     j=100
...     print(f'Not Valid: {j}')
Valid: 0

I have tried it on v3.12-win, v3.13-win and v3.14-win all of them gave the same results.

CPython versions tested on:

3.12

Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingThe issue will be closed if no feedback is providedtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions