sqlalchemy / sqlalchemy2-stubs

PEP-484 typing stubs for SQLAlchemy 1.4
MIT License
158 stars 41 forks source link

Columns with `nullable=False` are typed as optional #198

Open peteris-zealid opened 2 years ago

peteris-zealid commented 2 years ago

Describe the bug Table columns have optional[T] type even when they are defined with nullable=False

Expected behavior Expected for type to be just "builtins.str" (not optional)

To Reproduce

# Most of this is copy pasted from documentation
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import select
from sqlalchemy.orm import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)  #  <------------ Added nullable=False here

some_user = User(id=5, name='user')

reveal_type(some_user.name)  # <-------- Revealed type is "Union[builtins.str, None]" 

# Expected for type to be just "builtins.str" (not optional)

Versions.

Have a nice day! Thank you, you too. You do not see this a lot on the internet. Really appreciate it.

zzzeek commented 2 years ago

if you are using the mypy plugin, this is expected for the 1.4 series, see https://docs.sqlalchemy.org/en/14/orm/extensions/mypy.html#introspection-of-columns-based-on-typeengine

in 2.0 we will be using a completely different approach for this.

peteris-zealid commented 2 years ago

You are correct. Sorry for not reading the manual. You should probably close the issue now.

zzzeek commented 2 years ago

no worries at all , i will likely be switching this behavior for 2.0's approach (which won't use the plugin).