Skip to main content

SemanticSyntaxErrorKind

Enum SemanticSyntaxErrorKind 

Source
pub enum SemanticSyntaxErrorKind {
Show 36 variants LazyImportNotAllowed { context: LazyImportContext, kind: LazyImportKind, }, LazyImportStar, LazyFutureImport, 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§

§

LazyImportNotAllowed

Represents a lazy import statement in an invalid context.

§

LazyImportStar

Represents the use of lazy from ... import *.

§

LazyFutureImport

Represents the use of lazy from __future__ import ....

§

LateFutureImport

Represents the use of a __future__ import after the beginning of a file.

§Examples
from pathlib import Path

from __future__ import annotations

This 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,)  # SyntaxError

A starred assignment target can only occur within a tuple or list:

b, *a = 1, 2, 3
(*a,) = 1, 2, 3
[*a] = 1, 2, 3
§

WriteToDebug(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 x
§

DuplicateMatchKey(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) ':' pattern

But 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 a

While 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 declaration

This 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.

Fields

§name: String
§start: TextSize
§

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

See LoadBeforeGlobalDeclaration.

Fields

§name: String
§start: TextSize
§

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]  # error

await 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 okay

This 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: ...      # error
§

DuplicateParameter(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

Source§

fn clone(&self) -> SemanticSyntaxErrorKind

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for SemanticSyntaxErrorKind

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl GetSize for SemanticSyntaxErrorKind

Source§

fn get_heap_size(&self) -> usize

Determines how many bytes this object occupies inside the heap. Read more
Source§

fn get_heap_size_with_tracker<TRACKER>( &self, tracker: TRACKER, ) -> (usize, TRACKER)
where TRACKER: GetSizeTracker,

Determines how many bytes this object occupies inside the heap while using a tracker. Read more
Source§

fn get_stack_size() -> usize

Determines how may bytes this object occupies inside the stack. Read more
Source§

fn get_size(&self) -> usize

Determines the total size of the object. Read more
Source§

fn get_size_with_tracker<T>(&self, tracker: T) -> (usize, T)
where T: GetSizeTracker,

Determines the total size of the object while using a tracker. Read more
Source§

impl Hash for SemanticSyntaxErrorKind

Source§

fn hash<__H>(&self, state: &mut __H)
where __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for SemanticSyntaxErrorKind

Source§

fn eq(&self, other: &SemanticSyntaxErrorKind) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for SemanticSyntaxErrorKind

Source§

impl StructuralPartialEq for SemanticSyntaxErrorKind

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T, U> ExactFrom<T> for U
where U: TryFrom<T>,

Source§

fn exact_from(value: T) -> U

Source§

impl<T, U> ExactInto<U> for T
where U: ExactFrom<T>,

Source§

fn exact_into(self) -> U

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T, U> OverflowingInto<U> for T
where U: OverflowingFrom<T>,

Source§

impl<T, U> RoundingInto<U> for T
where U: RoundingFrom<T>,

Source§

impl<T, U> SaturatingInto<U> for T
where U: SaturatingFrom<T>,

Source§

impl<T> ToDebugString for T
where T: Debug,

Source§

fn to_debug_string(&self) -> String

Returns the String produced by Ts Debug implementation.

§Examples
use malachite_base::strings::ToDebugString;

assert_eq!([1, 2, 3].to_debug_string(), "[1, 2, 3]");
assert_eq!(
    [vec![2, 3], vec![], vec![4]].to_debug_string(),
    "[[2, 3], [], [4]]"
);
assert_eq!(Some(5).to_debug_string(), "Some(5)");
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T, U> WrappingInto<U> for T
where U: WrappingFrom<T>,

Source§

fn wrapping_into(self) -> U

Source§

impl<T> PyThreadingConstraint for T