Argento
Argento

Reputation: 3

Creating a class for function storage

I'm working on a code for a certain database. I want to create some functions, that will make it easier to write things to the db and get things out of there. Anyway - I want to make some functions.

My first thought was to just open a new .py file, get all the functions in there, and then use:

from FileName import Function

and then use it, and it works. But, it's not that good if have a lot of functions, because I will need to import each function I want manually:

from FileName import Function1 from FileName import Function2 from FileName import Function3

In contrast, when I use import random I can just use random.func in the code itself and carry on.

A friend suggested creating a class. I didn't think of that, since I'm not trying to create an object. So for example, In my current class code:

import sqlite3

conn = sqlite3.connect('asfan.db')
c = conn.cursor()

class Manager:

def save_chunk():
    c.execute("INSERT INTO DATA_CHUNKS VALUES(234, 'hello', '20190617', 'article')")
    conn.commit()
    c.close()
    conn.close()

and inside the main I just call import Manager from File and it works fine. But PyCharm doesn't really like the function I've written, because the method has no first parameter (PyCharm suggests "Self") and is static.

So is this the right way to "store" functions? I would love some help and references to learn about what I'm looking for.

Upvotes: 0

Views: 286

Answers (1)

kungphu
kungphu

Reputation: 4849

Using a class solely for function storage is not something I'd recommend. You'd need to either create an instance of it to call functions on (with the instance itself not mattering) or making every function a static or class method, which is also not good practice.

Generally, for importing functions, you can do that in a single line.

from module_name import fn_one, fn_two, fn_three

For a lot of really good standards regarding naming and imports, among other things, I highly recommend reading and adopting PEP 8.

I don't know if you intended that "class code" to all be the contents of a single file, but you should be careful about opening and closing resources in different contexts; if someone imported that file, a database connection would be opened, but it would not be closed unless save_chunk was called (and then the connection would no longer be available).

In this particular case, a class may make sense if you go a little further and use it to manage your database connection. A context manager is a common, useful way to manage setup and teardown for things like database connections.

This is already part of Python for SQLite, so you could subclass sqlite.Connection if you wanted to both take advantage of its context manager and add utility functions.

from sqlite3 import Connection


class SQLiteConnection(Connection):
    def test_schema(self):
        self.execute('CREATE TABLE test (name, location);')

    def test_populate(self):
        self.execute('''
            INSERT INTO test
            VALUES ('kungphu', 'Tokyo'),
                   ('Argento', 'Jerusalem')
        ''')

    def test_select(self):
        return self.execute('SELECT * from test')

Example usage:

>>> from scm import SQLiteConnection
>>> 
>>> with SQLiteConnection(':memory:') as conn:
...     conn.test_schema()
...     conn.test_populate()
...     for row in conn.test_select():
...         print(row)
... 
('kungphu', 'Tokyo')
('Argento', 'Jerusalem')

The methods I added here are... pretty silly, and definitely not a good way to handle fixtures or testing. They're just to illustrate how you could go about doing this if it makes sense in your use case.

Upvotes: 1

Related Questions