Skip to content Skip to sidebar Skip to footer

Hiding Implementation Files In A Package

I have a module called spellnum. It can be used as a command-line utility (it has the if __name__ == '__main__': block) or it can be imported like a standard Python module. The mod

Solution 1:

How about keeping spellnum.py?

spellnum.py
spelling/
  __init__.py
  en.py
  es.py

Solution 2:

Your problem is, that the package is called the same as the python-file you want to execute, thus importing

from spellnum import spellnum_en

will try to import from the file instead of the package. You could fiddle around with relative imports, but I don't know how to make them work with __import__, so I'd suggest the following:

def __init__(self, lang="en"):
    mod = "spellnum_" + lang
    module = None
    if __name__ == '__main__':
        module = __import__(mod)
    else:
        package = getattr(__import__("spellnum", fromlist=[mod]), mod)

Post a Comment for "Hiding Implementation Files In A Package"