Namespaces inside a class in Python3

I am new to Python and I wonder if there is a way to combine 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 will have many very similar methods (only different URIs), so although it would be nice to place them in several subspaces that belong to the categories of API requests. In other words, I want to create namespaces inside the class. I don't know if this is possible in Python and I know what to look for on Google.

I would be grateful for any help.

+8
python namespaces class
source share
1 answer

One way to do this is to define subspace and another_subspace as properties that return objects that 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() 

What does what you want to do:

 >>> 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 on, you can make a SubSpaceClass singleton, but I doubt the performance gain is worth it.

+2
source share

All Articles