Python Module with a dash, or hyphen (-) in its name

前端 未结 3 508
抹茶落季
抹茶落季 2020-11-28 12:43

I have an existing python module with a dash in its name, foo-bar.py

Changing the module name is something I would prefer to avoid as the module is shared, and I wou

相关标签:
3条回答
  • 2020-11-28 12:58

    I know this question has already been answered to satisfaction of the asker, but here is another answer which I believes has some merit above using __import__().

    import importlib
    mod = importlib.import_module("path.to.my-module")
    # mod.yourmethod()
    

    According to the docs:

    "This provides an implementation of import which is portable to any 
    Python interpreter. This also provides an implementation which is 
    easier to comprehend than one implemented in a programming language 
    other than Python."
    

    Python 2.7 + only

    0 讨论(0)
  • 2020-11-28 13:01

    Try using underscore instead of a hyphen.

    import pymysql_utils

    worked for me even though import pymysql-utils was the name of the module used by pip

    0 讨论(0)
  • 2020-11-28 13:14

    You can do that using __import__(). For example:

    foobar = __import__("foo-bar")
    

    But you really should rename the module instead. That way you can avoid confusion where the filename of the module is different from the identifier used in the program.

    0 讨论(0)
提交回复
热议问题