3

I've seen (and once used) this idiom a few times in Python:

# At the end of a module:
if __name__ == '__main__':
    main()  # or whatever your entry point looks like, this line isn't important
else:
    sys.modules[__name__] = SomeClass()

Usually, SomeClass will implement one or more magic methods, to allow code like this:

import mod
with mod:
    pass
foo = mod[bar]
mod()
# etc.

In my specific case, the module had previously acted a lot like an immutable mapping (having a top-level lookup() function of one argument), and I wanted to provide it with standard syntax for iteration, key lookup, etc. I felt this made more sense than writing several top-level functions that implemented all the same features as a mapping but with less familiar names.

I suppose my question is whether this is a pattern or an antipattern. Singletons themselves are often bad design, but if you're going to be using a module-as-singleton anyway, is this a good way to implement it?

  • 1
    Why can't you just create an instance of SomeClass inside the module and assign it to a variable? It only takes one additional line for the client code to assign that to a top-level variable in its own module. This sort of trickery is more trouble than it's worth. – Doval Nov 13 '14 at 20:33
  • @Doval: The module doesn't contain a mapping, it literally is a mapping; its entire purpose is turning keys into values. Why pretend otherwise? – Kevin Nov 13 '14 at 20:35
  • 4
    For the same reason you treat objects as objects and not as the dictionaries they truly are: consistency. Modules are things you import for its components. Python will let you do all sorts of stupid things, but that doesn't mean you should do them. Doing something highly unconventional makes it a lot harder for other people to understand what you're doing, and you really don't need that in a language with dynamic typing and all sorts of scary reflection capabilities. – Doval Nov 13 '14 at 20:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.