2

I am reading this piece of code by Alex Martelli mentioned in this question. I understand that sys.modules[__name__] tells you what module you are currently at, but this line of code at the end of his constant.py really confuses me. What is the meaning and the point of having such a statement that declares the current module by the end of the file?

# Put in const.py...:
class _const:
    class ConstError(TypeError): pass
    def __setattr__(self,name,value):
        if self.__dict__.has_key(name):
            raise self.ConstError, "Can't rebind const(%s)"%name
        self.__dict__[name]=value
import sys
sys.modules[__name__]=_const() #this I don't understand
# that's all -- now any client-code can
import const

Basically, my question is that in my opinion this line of code does not do anything; am I understanding it wrong? Since in Python you don't have to put class definitions in separate files, I argue that I don't really need two modules unless I want to reuse the class "const." Then in this case sys.moldules[__name__]=_const() is not necessary either... Am I understanding it correctly?

K.Mole
  • 123
  • 1
  • 11

1 Answers1

2

I believe it is binding an instance to the module. So when you do import const, you actually get an instance of the class _const.

This allows you to call methods on it. Like, for example, the __setattr__, where in this case it checks that you only bind a variable once.

Pablo
  • 358
  • 1
  • 13
  • So without that line of code, doing `import const` will run that python module, instead of getting an instance of the class then? – K.Mole Jul 24 '19 at 19:37
  • yes, `import const` will behave like a normal package import, with a class called `_const` defined inside. And given the underscore prefix, it would not be imported through `from const import *` (from the [docs](https://docs.python.org/3/tutorial/classes.html#private-variables)) – Pablo Jul 24 '19 at 19:48