Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python type annotation for rare objects, for example psycopg2 objects

I know about builtin types. But how I can specify rare objects, a db connection object for example?

def get_connection_and_cursor() -> tuple[psycopg2.extensions.cursor, psycopg2.extensions.connection]:
    connection = psycopg2.connect(dbname=db_name, user=db_user, password=db_password, host='127.0.0.1', port="5432")
    # connection.autocommit = True
    cursor = connection.cursor()
    return connection, cursor

Checking the type, here is the output of:

  • type(cursor): psycopg2.extensions.cursor and
  • type(connection): psycopg2.extensions.connection.

What should I do with it?

like image 995
kukuruza Avatar asked Mar 30 '26 20:03

kukuruza


1 Answers

These are custom types (classes) defined by psycopg2.

psycopg2.extensions.cursor represents a cursor, and

psycopg2.extensions.connection represents a connnection.


Even builtin-types are classes under-the-hood. Try type(3) and you will see it is a class of type int.

Create your own class, defining variable and methods like so:

class CustomType:
    def __init__(self):   # this is the constructor
        self.x = 3        # this is an instance variable of the class

    def update(self):     # this is an instance method of the class
        self.x += 1       # access instance fields with self param

    @staticmethod         # this is a static method of the class
    def __str__():        # toString equivalent
        return 'abc' 
like image 171
rnath Avatar answered Apr 01 '26 10:04

rnath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!