0

I am attempting to achieve a form of namespace-like behavior in a single Python file. I am considering using nested classes and class redefinition. I am aware that this approach might have issues, but I would like to understand whether this method could be considered feasible. Please note that I am constrained to writing all the code within a single Python file. Additionally, I am wondering if I should take into account naming conventions from the C language. Here is a reference code snippet to illustrate my approach:

class NAMESPACE:
    a = 1
    class NAMESPACEBaseException(Exception):
        ...
    class NAMESPACEApiHttpException(SMTHBaseException):
        ...
    print(a)

class NAMESPACE(NAMESPACE):
    @staticmethod
    def slist(uid, key):
        ...
    print(NAMESPACE.a)
try:
    raise NAMESPACE.NAMESPACEApiHttpException("raise NAMESPACE.NAMESPACEApiHttpException")
except NAMESPACE.NAMESPACEApiHttpException as e:
    print(e)
    print(SMTH.slist(0, 0))
finally:
    del NAMESPACE

I read these: is-it-a-good-idea-to-using-class-as-a-namespace-in-python

Would using this approach have any potential pitfalls or drawbacks? Can I use C language's naming conventions as a reference for structuring my classes in this manner? Are there any alternatives I should consider for achieving a similar namespace-like behavior while keeping all the code in a single Python file?

VincentGe
  • 3
  • 3
  • 1
    This isn't even remotely like python; it's very hard to correct your understanding based on what you've shown. The fact you keep mentioning that it's a single file is confusing - it makes absolutely no difference. I can't think of any library that couldn't already be written as a single file if you really wanted, it would just be totally unworkable from a human standpoint – roganjosh Aug 31 '23 at 11:34
  • Ok, I think I need to clarify my working environment, the code is written in Jupyterlab, I can only use a .pynb file to store my code, I need to process a lot of data, and I need to constantly try to run my code (the error is unknown), which is different from normal .py files! I understand that I shouldn't do this in .py, but I have to, I need to isolate variables with the same name this way, and if I don't, I need to use very long variable names. Maybe there are other ways? @roganjosh – VincentGe Aug 31 '23 at 12:35

0 Answers0