Search code examples
pythonpython-3.xclassnamespaces

Namespaces inside class in Python3


I am new to Python and I wonder if there is any way to aggregate methods into 'subspaces'. I mean something similar to this syntax:

smth = Something()
smth.subspace.do_smth()
smth.another_subspace.do_smth_else()

I am writing an API wrapper and I'm going to have a lot of very similar methods (only different URI) so I though it would be good to place them in a few subspaces that refer to the API requests categories. In other words, I want to create namespaces inside a class. I don't know if this is even possible in Python and have know idea what to look for in Google.

I will appreciate any help.


Solution

  • One way to do this is by defining subspace and another_subspace as properties that return objects that provide do_smth and do_smth_else respectively:

    class Something:
        @property
        def subspace(self):
            class SubSpaceClass:
                def do_smth(other_self):
                    print('do_smth')
            return SubSpaceClass()
    
        @property
        def another_subspace(self):
            class AnotherSubSpaceClass:
                def do_smth_else(other_self):
                    print('do_smth_else')
            return AnotherSubSpaceClass()
    

    Which does what you want:

    >>> smth = Something()
    >>> smth.subspace.do_smth()
    do_smth
    >>> smth.another_subspace.do_smth_else()
    do_smth_else
    

    Depending on what you intend to use the methods for, you may want to make SubSpaceClass a singleton, but i doubt the performance gain is worth it.