简体   繁体   中英

Type hinting return -> object

I have a function to get a SQLAchemy Engine connection:

def get_engine_connection(
    username: str,
    password: str,
    database: str,
    host: str = "localhost",
    port: str = "3306",
) -> object:
    try:
        engine = create_engine(
            f"mysql+pymysql://{username}:{password}@{host}:{port}/{database}",
            echo=False,
            poolclass=NullPool,
        )
        return engine
    except Exception as error:
        print(error)

If all goes well, the return type will be:

<class 'sqlalchemy.engine.base.Engine'>

Is it correct for me to say that the return of my function will be an object or is there no type hint object?

def get_engine_connection( // ) -> object:
    //

This page goes over the Any and object types. In particular, it says

Use object to indicate that a value could be any type in a typesafe manner. Use Any to indicate that a value is dynamically typed.

The return value of your function isn't dynamically typed, so it sounds like object is appropriate in this case. However it would be better to use sqlalchemy.engine.base.Engine itself if possible, likely as type[sqlalchemy.engine.base.Engine] as pointed out in this comment .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM