I am working in a gitlab API library in python. It started as a pet project to understand more about modules so I didn't think about it at the start and started writing all the code in the __init__.py inside the module dir.
Of course, now that is has grown, I can see that the organization is quite poor, there is way to much method for one class, testing has become difficult, checking the code is quite confusing as there is a lot in there.
So I have thougth of splitting it in several submodules, you know the tipical from X import Y so the code is more readable, testeable, smaller but I have found that I have absolutely no idea how to implement it as I got plenty of shared variables and such all over the class with all methods using class variables....
So, is there any good documentation on creating python modules with "submodules"? How to share objects variables between classes? Any clear modules that I should be checking that have the login on one submodule and the functions in other, for example?
Cheers!
In general this is referred to as 'refactoring'. Lots of good Python and general computer science literature out there if you look for it.
Up front based on what you have described it sounds like you need to stop using the data stored in your classes directly and start using member functions for access.
class A(object):
def __init__(self, value):
self.value = value
a = A(1)
print a.value
a.value = 5
print a.value
See how I modified value directly? This can lead to all kinds of assumptions in code. You are better off with using methods to retrieve values and make changes. Note, mindless getFoo/setFoo is also bad. Try to have your methods expose behavior not knobs to twist.
class A(object):
def __init__(self, value):
self.value = value
def is_safe(self):
if value > 10:
return False
return True
def increase_value(self, increment):
if increment <= 0:
raise ValueError("only positive increments are allowed")
self.value += increment
See how the logic is self contained? We never want an instance of A to get smaller so we only allow increments and name the function increase to indicate this. setValue
does not tell what or why.
As for modules and submodules, group matching things together. "matching" is based on your own code's needs. All of the user functions? All of the DB functions? Putting things in modules allows for the possibility of plugging in a different module with the same exposed API. Think authentication from a SQL DB or from a local text file.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments