Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a Python class among multiple modules using packages

Tags:

python

I wrote some code in python as a class, but now I'm trying to prepare it for distribution as a package and I was having some trouble with figuring out how the different pieces should fit together.

So, as I originally wrote the code I had a class with a few functions in it, including an __init__ function. I've now split each of these functions into its own file named with the function name, but I'm unsure where to put the init function, since it takes arguments. An example is below.

Original format:

class className(object):

    def __init__(self, arg1, arg2):
         self.arg1 = arg1
         self.arg2 = arg2

    def func1(self):

    def func2(self, arg3):

With a usage of:

import name

a = name.className(arg1, arg2)
a.func1()
a.func2(arg3)

Now the file tree is:

Name/
    /className
        __init__.py
        func1.py
        func2.py

And on to include the other functions. I would like to keep the same basic usage pattern as the original.

Now, the question I have is where that __init__ function should go? Inside the __init__.py file? Somewhere else? The other issue is I wanted to put some imports in the __init__.py file; I know they should go in the __init__.py file, but I don't know how they relate to the __init__ function. Any help is appreciated.

like image 584
user1074057 Avatar asked Jan 16 '23 03:01

user1074057


1 Answers

You can't split a class across multiple files. A package should contain multiple modules, which are files containing code (complete classes, functions, etc...).

The __init__.py file is run when the package is imported (although it's rare it is used to actually execute much code) and tells Python the directory is a package, it's not the constructor for a class.

A package (folder) should be a collection of packages and modules, while a module (file) will be a collection of code.

An example of a normal hierarchy:

- somepackage (Folder)
    - __init__.py (File)
    - somemodule.py (File)
        - SomeClass (Code)
        - some_function (Code)

As a final note, I say you can't split a class across multiple files - technically you could do this by monkey patching functions into the class or some other such weirdness, but you'd never want to as it would obscure your code a lot.

like image 78
Gareth Latty Avatar answered Jan 20 '23 01:01

Gareth Latty