Unique Kiddo
Unique Kiddo

Reputation: 45

Is cursor() a class inside the connect() class in sqlite3 module in python?

I recently started learning sqlite3 in python and found the cursor() to be confusing.

import sqlite3
conn=sqlite3.connect('datebase.db')
c=conn.cursor()
c.execute('')

Is cursor() a nested class inside connect() or is it a classmethod or neither. Please explain.

Upvotes: 0

Views: 593

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124748

Don't confuse methods with classes or instances. Just because a method returns an instance, doesn't mean that that class lives inside another class.

A method runs some code, that code can create instances of any class they like. The SQLite library does this, roughly (the exact code is more complex, and written in C):

class Connection:
    def cursor(self):
        cursor = Cursor(self)
        if self.row_factory is not None:
            cursor.row_factory = self.row_factory
        return cursor

class Cursor:
    def __init__(self, connection):
        self.connection = connection
        # set other attributes for the instance

So the Connection().cursor() method returns an object that holds a reference back to the connection, but the class itself is defined elsewhere.

The module gives you access to those classes directly; you can create the cursor just the same way:

>>> import sqlite3
>>> sqlite3.Connection
<class 'sqlite3.Connection'>
>>> sqlite3.Cursor
<class 'sqlite3.Cursor'>
>>> conn = sqlite3.connect(':memory:')
>>> conn
<sqlite3.Connection object at 0x105938570>
>>> sqlite3.Cursor(conn)
<sqlite3.Cursor object at 0x105bcbea0>

However, using the Connection().cursor() method ensures you won't forget to properly attach it to the right connection, and the Connection.cursor() method also does some internal clean-up that's important for memory management (I omitted it above, but you can study the C code I linked).

Note that Python does not have a privacy model like C# or Java have. In those languages you can use a nested, inner class to provide privilege access to attributes that other code is not allowed to use. In Python, nested classes are just attributes on the parent class, nothing more. There usually is very little use for such nesting, and only makes things less readable.

Upvotes: 1

Prahlad Yeri
Prahlad Yeri

Reputation: 3663

As Carles Explained, .cursor() is the method here that returns the object of type Cursor which is a class. To verify this for yourself, open a temporary connection using the python interpreter:

import sqlite3
conn = sqlite3.connection(':memory:')
c = conn.cursor()

Now, After getting the cursor, just type:

type(c)

And you will get:

<class 'sqlite3.Cursor'>

Upvotes: 0

Related Questions