sqltypes.Enum not generic enough

Aperta
#11,597 0 commenti 1 reazione 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

  • #13492 di @waterWang — chiusa senza merge

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
45/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Ferma
Stack tecnologico
python
Ambito
databases

Direzione di ricerca

Inizia in lib/sqlalchemy/sql/sqltypes.py, nelle definizioni di String e Enum, quindi leggi la discussione collegata sull’errore di pyright e sulle modifiche proposte al tipaggio. Controlla l’esempio che usa Enum(MyEnum, native_enum=False) e column_property; il lavoro è completato quando il tipaggio generico di Enum supporta tale utilizzo senza la segnalazione di pyright riportata.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

bug datatypes typing
Discussed in https://github.com/sqlalchemy/sqlalchemy/discussions/11548

The generic type for Enum needs to be a typevar for pyright:

from __future__ import annotations

import enum

from sqlalchemy import Enum
from sqlalchemy import func
from sqlalchemy.orm import column_property
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column

class MyEnum(enum.Enum):
    one = "one"
    two = "two"



class Base(DeclarativeBase):
    pass


class A(Base):
    __tablename__ = "a"

    id: Mapped[int] = mapped_column(primary_key=True)
    data: Mapped[MyEnum] = column_property(
        func.some_func(type_=Enum(MyEnum, native_enum=False))
    )


image

seems to pass in mypy

a quick fix looks like:

@@ -1179,8 +1186,9 @@ class SchemaType(SchemaEventTarget, TypeEngineMixin):
         elif dialect.name not in variant_mapping:
             return _we_are_the_impl(variant_mapping["_default"])
 
+_TEE = TypeVar("_TEE", bound=Union[str, enum.Enum])
 
-class Enum(String, SchemaType, Emulated, TypeEngine[Union[str, enum.Enum]]):
+class Enum(String, SchemaType, Emulated, TypeEngine[_TEE]):
     """Generic Enum Type.
 
     The :class:`.Enum` type provides a set of possible string values
@@ -1483,7 +1491,7 @@ class Enum(String, SchemaType, Emulated, TypeEngine[Union[str, enum.Enum]]):
             self.enum_class = None
             return enums, enums
 
-    def _resolve_for_literal(self, value: Any) -> Enum:
+    def _resolve_for_literal(self, value: Any) -> Enum[Any]:
         tv = type(value)
         typ = self._resolve_for_python_type(tv, tv, tv)
         assert typ is not None
@@ -1494,7 +1502,7 @@ class Enum(String, SchemaType, Emulated, TypeEngine[Union[str, enum.Enum]]):
         python_type: Type[Any],
         matched_on: _MatchedOnType,
         matched_on_flattened: Type[Any],
-    ) -> Optional[Enum]:
+    ) -> Optional[Enum[Any]]:
         # "generic form" indicates we were placed in a type map
         # as ``sqlalchemy.Enum(enum.Enum)`` which indicates we need to
         # get enumerated values from the datatype
@@ -1538,7 +1546,7 @@ class Enum(String, SchemaType, Emulated, TypeEngine[Union[str, enum.Enum]]):
 
         kw["length"] = NO_ARG if self.length == 0 else self.length
         return cast(
-            Enum,
+            Enum[Any],
             self._generic_type_affinity(_enums=enum_args, **kw),  # type: ignore  # noqa: E501
         )

to go further we might want to remove String from Enum's inherits, since pyright still complains about the signature

diff --git a/lib/sqlalchemy/sql/sqltypes.py b/lib/sqlalchemy/sql/sqltypes.py
index c20df07a6..f948ee01d 100644
--- a/lib/sqlalchemy/sql/sqltypes.py
+++ b/lib/sqlalchemy/sql/sqltypes.py
@@ -256,6 +256,13 @@ class String(Concatenable, TypeEngine[str]):
         return dbapi.STRING
 
 
+if TYPE_CHECKING:
+    class StringNoGeneric(Concatenable):
+        pass
+else:
+    StringNoGeneric = String
+
+
 class Text(String):
     """A variably sized string type.
 
@@ -1179,8 +1186,9 @@ class SchemaType(SchemaEventTarget, TypeEngineMixin):
         elif dialect.name not in variant_mapping:
             return _we_are_the_impl(variant_mapping["_default"])
 
+_TEE = TypeVar("_TEE", bound=Union[str, enum.Enum])
 
-class Enum(String, SchemaType, Emulated, TypeEngine[Union[str, enum.Enum]]):
+class Enum(StringNoGeneric, SchemaType, Emulated, TypeEngine[_TEE]):
     """Generic Enum Type.
 
     The :class:`.Enum` type provides a set of possible string values
@@ -1483,7 +1491,7 @@ class Enum(String, SchemaType, Emulated, TypeEngine[Union[str, enum.Enum]]):
             self.enum_class = None
             return enums, enums
 
-    def _resolve_for_literal(self, value: Any) -> Enum:
+    def _resolve_for_literal(self, value: Any) -> Enum[Any]:
         tv = type(value)
         typ = self._resolve_for_python_type(tv, tv, tv)
         assert typ is not None
@@ -1494,7 +1502,7 @@ class Enum(String, SchemaType, Emulated, TypeEngine[Union[str, enum.Enum]]):
         python_type: Type[Any],
         matched_on: _MatchedOnType,
         matched_on_flattened: Type[Any],
-    ) -> Optional[Enum]:
+    ) -> Optional[Enum[Any]]:
         # "generic form" indicates we were placed in a type map
         # as ``sqlalchemy.Enum(enum.Enum)`` which indicates we need to
         # get enumerated values from the datatype
@@ -1538,7 +1546,7 @@ class Enum(String, SchemaType, Emulated, TypeEngine[Union[str, enum.Enum]]):
 
         kw["length"] = NO_ARG if self.length == 0 else self.length
         return cast(
-            Enum,
+            Enum[Any],
             self._generic_type_affinity(_enums=enum_args, **kw),  # type: ignore  # noqa: E501
         )
 

Lingua principale
Python
Stelle
12.3k
Fork
1.8k
Merge medio
2g 10h
PR unite (30g)
9

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di sqlalchemy/sqlalchemy

Tutte le issue di sqlalchemy/sqlalchemy

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.