Skip to content

Add ternary conditional operator (?:) and $-prefix None-declaration syntax #155087

Description

@RAJ0793

Feature or enhancement

Proposal:

Motivation

Python's existing x if cond else y ternary requires more characters and
some developers coming from C-family languages find cond ? x : y more
concise for simple one-line conditionals. Additionally, a $name shorthand
for declaring a variable pre-initialized to None (similar to Dart's
declaration semantics) could reduce boilerplate for patterns like:

x = None
...
x = some_value

Proposed syntax

$name              # equivalent to: name = None
cond ? a : b        # equivalent to: a if cond else b

Current status

I have a working prototype implemented at the grammar level
(Grammar/python.gram) as a proof of concept, tested against CPython's
own PEG parser generator, covering: precedence, nested ternaries,
list/dict/set comprehensions, generator expressions, lambda, walrus,
keyword arguments — with one known issue (f-string compatibility)
still being investigated.

Branch: https://github.com/RAJ0793/cpython/tree/features-clean

Questions for the community

  1. Is there existing prior art / rejected PEPs covering this exact syntax?
  2. Would this need a formal PEP given it's new operator syntax?
  3. Is there appetite for this kind of shorthand in the language, or does
    it conflict with "there should be one obvious way to do it"?

I'm a newer contributor and want to follow the right process — happy to
close this if it's already been discussed and rejected before.

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions