pub enum SemanticSyntaxErrorKind {
Show 33 variants
LateFutureImport,
ReboundComprehensionVariable,
DuplicateTypeParameter,
MultipleCaseAssignment(Name),
IrrefutableCasePattern(IrrefutablePatternKind),
SingleStarredAssignment,
WriteToDebug(WriteToDebugKind),
InvalidExpression(InvalidExpressionKind, InvalidExpressionPosition),
DuplicateMatchKey(String),
DuplicateMatchClassAttribute(Name),
LoadBeforeGlobalDeclaration {
name: String,
start: TextSize,
},
LoadBeforeNonlocalDeclaration {
name: String,
start: TextSize,
},
InvalidStarExpression,
AsyncComprehensionInSyncComprehension(PythonVersion),
YieldOutsideFunction(YieldOutsideFunctionKind),
ReturnOutsideFunction,
AwaitOutsideAsyncFunction(AwaitOutsideAsyncFunctionKind),
DuplicateParameter(String),
NonlocalDeclarationAtModuleLevel,
NonlocalAndGlobal(String),
AnnotatedGlobal(String),
AnnotatedNonlocal(String),
YieldFromInAsyncFunction,
NonModuleImportStar(String),
MultipleStarredExpressions,
FutureFeatureNotDefined(String),
BreakOutsideLoop,
ContinueOutsideLoop,
GlobalParameter(String),
DifferentMatchPatternBindings,
NonlocalWithoutBinding(String),
TypeParameterDefaultOrder(String),
ReturnInGenerator,
}Variants§
LateFutureImport
Represents the use of a __future__ import after the beginning of a file.
§Examples
from pathlib import Path
from __future__ import annotationsThis corresponds to the late-future-import (F404) rule in ruff.
ReboundComprehensionVariable
Represents the rebinding of the iteration variable of a list, set, or dict comprehension or a generator expression.
§Examples
[(a := 0) for a in range(0)]
{(a := 0) for a in range(0)}
{(a := 0): val for a in range(0)}
{key: (a := 0) for a in range(0)}
((a := 0) for a in range(0))DuplicateTypeParameter
Represents a duplicate type parameter name in a function definition, class definition, or type alias statement.
§Examples
type Alias[T, T] = ...
def f[T, T](t: T): ...
class C[T, T]: ...MultipleCaseAssignment(Name)
Represents a duplicate binding in a case pattern of a match statement.
§Examples
match x:
case [x, y, x]: ...
case x as x: ...
case Class(x=1, x=2): ...IrrefutableCasePattern(IrrefutablePatternKind)
Represents an irrefutable case pattern before the last case in a match statement.
According to the Python reference, “a match statement may have at most one irrefutable case block, and it must be last.”
§Examples
match x:
case value: ... # irrefutable capture pattern
case other: ...
match x:
case _: ... # irrefutable wildcard pattern
case other: ...SingleStarredAssignment
Represents a single starred assignment target outside of a tuple or list.
§Examples
*a = (1,) # SyntaxErrorA starred assignment target can only occur within a tuple or list:
b, *a = 1, 2, 3
(*a,) = 1, 2, 3
[*a] = 1, 2, 3WriteToDebug(WriteToDebugKind)
Represents a write to __debug__. This includes simple assignments and deletions as well
other kinds of statements that can introduce bindings, such as type parameters in functions,
classes, and aliases, match arms, and imports, among others.
§Examples
del __debug__
__debug__ = False
def f(__debug__): ...
class C[__debug__]: ...See BPO 45000 for more information.
InvalidExpression(InvalidExpressionKind, InvalidExpressionPosition)
Represents the use of an invalid expression kind in one of several locations.
The kinds include yield and yield from expressions and named expressions, and locations
include type parameter bounds and defaults, type annotations, type aliases, and base class
lists.
§Examples
type X[T: (yield 1)] = int
type Y = (yield 1)
def f[T](x: int) -> (y := 3): return xDuplicateMatchKey(String)
Represents a duplicate key in a match mapping pattern.
The CPython grammar allows keys in mapping patterns to be literals or attribute accesses:
key_value_pattern:
| (literal_expr | attr) ':' patternBut only literals are checked for duplicates:
>>> match x:
... case {"x": 1, "x": 2}: ...
...
File "<python-input-160>", line 2
case {"x": 1, "x": 2}: ...
^^^^^^^^^^^^^^^^
SyntaxError: mapping pattern checks duplicate key ('x')
>>> match x:
... case {x.a: 1, x.a: 2}: ...
...
>>>§Examples
match x:
case {"x": 1, "x": 2}: ...DuplicateMatchClassAttribute(Name)
Represents a duplicate attribute name in a match class pattern.
§Examples
match x:
case Class(x=1, x=2): ...LoadBeforeGlobalDeclaration
Represents the use of a global variable before its global declaration.
§Examples
counter = 1
def increment():
print(f"Adding 1 to {counter}")
global counter
counter += 1§Known Issues
Note that the order in which the parts of a try statement are visited was changed in 3.13,
as tracked in Python issue #111123. For example, this code was valid on Python 3.12:
a = 10
def g():
try:
1 / 0
except:
a = 1
else:
global aWhile this more intuitive behavior aligned with the textual order was a syntax error:
a = 10
def f():
try:
pass
except:
global a
else:
a = 1 # SyntaxError: name 'a' is assigned to before global declarationThis was reversed in version 3.13 to make the second case valid and the first case a syntax error. We intentionally enforce the 3.13 ordering, regardless of the Python version, which will lead to both false positives and false negatives on 3.12 code that takes advantage of the old behavior. However, as mentioned in the Python issue, we expect code relying on this to be very rare and not worth the additional complexity to detect.
LoadBeforeNonlocalDeclaration
Represents the use of a nonlocal variable before its nonlocal declaration.
§Examples
def f():
counter = 0
def increment():
print(f"Adding 1 to {counter}")
nonlocal counter # SyntaxError: name 'counter' is used prior to nonlocal declaration
counter += 1§Known Issues
InvalidStarExpression
Represents the use of a starred expression in an invalid location, such as a return or
yield statement.
§Examples
def f(): return *x
def f(): yield *x
for _ in *x: ...
for *x in xs: ...AsyncComprehensionInSyncComprehension(PythonVersion)
Represents the use of an asynchronous comprehension inside of a synchronous comprehension before Python 3.11.
§Examples
Before Python 3.11, code like this produces a syntax error because of the implicit function scope introduced by the outer comprehension:
async def elements(n): yield n
async def test(): return { n: [x async for x in elements(n)] for n in range(3)}This was discussed in BPO 33346 and fixed in Python 3.11.
YieldOutsideFunction(YieldOutsideFunctionKind)
Represents the use of yield, yield from, or await outside of a function scope.
§Examples
yield and yield from are only allowed if the immediately-enclosing scope is a function
or lambda and not allowed otherwise:
yield 1 # error
def f():
[(yield 1) for x in y] # errorawait is additionally allowed in comprehensions, if the comprehension itself is in a
function scope:
await 1 # error
async def f():
await 1 # okay
[await 1 for x in y] # also okayThis last case is an error, but it has to do with the lambda not being an async function. For the sake of this error kind, this is okay.
§References
See PEP 255 for details on yield, PEP 380 for the extension to yield from, PEP 492
for async-await syntax, and PEP 530 for async comprehensions.
ReturnOutsideFunction
Represents the use of return outside of a function scope.
AwaitOutsideAsyncFunction(AwaitOutsideAsyncFunctionKind)
Represents the use of await, async for, or async with outside of an asynchronous
function.
§Examples
def f():
await 1 # error
async for x in y: ... # error
async with x: ... # errorDuplicateParameter(String)
Represents a duplicate parameter name in a function or lambda expression.
§Examples
def f(x, x): ...
lambda x, x: ...NonlocalDeclarationAtModuleLevel
Represents a nonlocal declaration at module level
NonlocalAndGlobal(String)
Represents the same variable declared as both nonlocal and global
AnnotatedGlobal(String)
Represents a type annotation on a variable that’s been declared global
AnnotatedNonlocal(String)
Represents a type annotation on a variable that’s been declared nonlocal
YieldFromInAsyncFunction
Represents the use of yield from inside an asynchronous function.
NonModuleImportStar(String)
Represents the use of from <module> import * outside module scope.
MultipleStarredExpressions
Represents the use of more than one starred expression in an assignment.
Python only allows a single starred target when unpacking values on the
left-hand side of an assignment. Using multiple starred expressions makes
the statement invalid and results in a SyntaxError.
FutureFeatureNotDefined(String)
Represents the use of a __future__ feature that is not defined.
BreakOutsideLoop
Represents the use of a break statement outside of a loop.
ContinueOutsideLoop
Represents the use of a continue statement outside of a loop.
GlobalParameter(String)
Represents a function parameter that is also declared as global.
Declaring a parameter as global is invalid, since parameters are already
bound in the local scope of the function. Using global on them introduces
ambiguity and will result in a SyntaxError.
DifferentMatchPatternBindings
Represents the use of alternative patterns in a match statement that bind different names.
Python requires all alternatives in an OR pattern (|) to bind the same set of names.
Using different names results in a SyntaxError.
§Example:
match 5:
case [x] | [y]: # error
...NonlocalWithoutBinding(String)
Represents a nonlocal statement for a name that has no binding in an enclosing scope.
TypeParameterDefaultOrder(String)
Represents a default type parameter followed by a non-default type parameter.
ReturnInGenerator
Represents a return statement with a value in an asynchronous generator.
Trait Implementations§
Source§impl Clone for SemanticSyntaxErrorKind
impl Clone for SemanticSyntaxErrorKind
Source§fn clone(&self) -> SemanticSyntaxErrorKind
fn clone(&self) -> SemanticSyntaxErrorKind
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for SemanticSyntaxErrorKind
impl Debug for SemanticSyntaxErrorKind
Source§impl GetSize for SemanticSyntaxErrorKind
impl GetSize for SemanticSyntaxErrorKind
Source§fn get_heap_size(&self) -> usize
fn get_heap_size(&self) -> usize
Source§fn get_heap_size_with_tracker<TRACKER: GetSizeTracker>(
&self,
tracker: TRACKER,
) -> (usize, TRACKER)
fn get_heap_size_with_tracker<TRACKER: GetSizeTracker>( &self, tracker: TRACKER, ) -> (usize, TRACKER)
tracker. Read moreSource§fn get_stack_size() -> usize
fn get_stack_size() -> usize
Source§fn get_size_with_tracker<T>(&self, tracker: T) -> (usize, T)where
T: GetSizeTracker,
fn get_size_with_tracker<T>(&self, tracker: T) -> (usize, T)where
T: GetSizeTracker,
tracker. Read moreSource§impl Hash for SemanticSyntaxErrorKind
impl Hash for SemanticSyntaxErrorKind
Source§impl PartialEq for SemanticSyntaxErrorKind
impl PartialEq for SemanticSyntaxErrorKind
impl Eq for SemanticSyntaxErrorKind
impl StructuralPartialEq for SemanticSyntaxErrorKind
Auto Trait Implementations§
impl Freeze for SemanticSyntaxErrorKind
impl RefUnwindSafe for SemanticSyntaxErrorKind
impl Send for SemanticSyntaxErrorKind
impl Sync for SemanticSyntaxErrorKind
impl Unpin for SemanticSyntaxErrorKind
impl UnsafeUnpin for SemanticSyntaxErrorKind
impl UnwindSafe for SemanticSyntaxErrorKind
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more