nowox
nowox

Reputation: 29066

How to organise Python related classes

I have currently this structure inside a file:

class Foo:
    __init__(self): 
       pass

class FooType(object):
    __init__(self, value):
       _foo = value
    __str__(self):
       print ">>%s<<" % self._foo

class FooException(Exception):
    pass

All the above classes are tightly related. My master class will have types, structures, enums all declared as a separated class with the prefix Foo. And as usual a custom exception should be declared for Foo. At the end of the day I will have a lot of related classes at the same level of other classes.

Is there a proper way to get a better structure? Perhaps a namespace can help, but I don't know how to use it.

Upvotes: 1

Views: 120

Answers (2)

porglezomp
porglezomp

Reputation: 1349

In Python, the idiomatic way to do namespaces is to use different modules. You should name your file foo.py, and then import that. Then you use it with foo.Exception and foo.Type. If you need to have a more complex module that needs more than one file, you should make a folder called foo and put an __init__.py file along with your other components of the module. For further documentation on using modules, see the docs.

Another solution is to use nested classes to provide a namespace. The chosen answer to this question about nested classes recommends them for the purpose of namespacing.

Upvotes: 3

jojonas
jojonas

Reputation: 1675

You could organize your classes in modules, just like the Python standard library does.

Upvotes: 1

Related Questions