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?

asked Nov 13, 2014 at 19:56
3
  • 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. Commented Nov 13, 2014 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? Commented Nov 13, 2014 at 20:35
  • 5
    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. Commented Nov 13, 2014 at 20:37

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.