1

I'm using the Pylance extension in VS Code, and I encountered a warning Variable not allowed in type expression. It seems that Pylance is not recognizing an imported class when used in a type expression.

Here is a simplified version of my code:

from dataclasses import dataclass
from typing import ClassVar

from marshmallow import Schema
from marshmallow_dataclass import add_schema


@add_schema
@dataclass(frozen=True)
class A:
    name: str

    Schema: ClassVar[type[Schema]] = Schema


A().Schema().load()

Pylance thinks that Schema used in type[Schema] is a variable name, not the imported class. If I use from __future__ import annotations - the warning disappears. And I want to resolve it so that I have useful highlights and code completion when the Schema is loaded.

0

1 Answer 1

1

This is as designed.

To quote the maintainer:

[...] this behavior isn't something you should rely on. The resolution order for type annotations at runtime is not well documented and can change based on the Python version and on various modes like from future import __annotations__. It's best to avoid shadowing the names of [other classes] in your code. If that's not possible, you should use unambiguous qualified names or type aliases to refer to the type you intend.

In other words, since using the Schema attribute is unnegotiable, you have three choices:

1. Use qualified name

import marshmallow

...
class A:
    ...
    Schema: ClassVar[type[marshmallow.Schema]] = marshmallow.Schema

2. Use an import alias

from marshmallow import Schema as MarshmallowSchema

...
class A:
    ...
    Schema: ClassVar[type[MarshmallowSchema]] = MarshmallowSchema

3. Use a type alias

from marshmallow import Schema

# Python 3.12+
type MarshmallowSchema = Schema

# Python 3.11-
from typing import TypeAlias
MarshmallowSchema: TypeAlias = Schema

...
class A:
    ...
    Schema: ClassVar[type[MarshmallowSchema]] = MarshmallowSchema
Sign up to request clarification or add additional context in comments.

2 Comments

I get that, but isn't there a workaround to add future scope without all those changes? Whole project was written on Pycharm which was handling it, now in VsCode I came across this error and want to somehow fix it without rewriting on each file manually
@user16965639 You can also quote the hint using a mass find & replace: Schema: 'ClassVar[type[Schema]]' = Schema. This has a slight disadvantage in terms of readability, but a possible choice nonetheless.

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.