Import Local module over global python

后端 未结 2 1563
生来不讨喜
生来不讨喜 2021-01-12 21:36

I have a 2 python files. One is trying to import the second. My problem is that the second is named math.py. I can not rename it. When I attempt to call a function that is l

2条回答
  •  野的像风
    2021-01-12 22:01

    Python processes have a single namespace of loaded modules. If you (or any other module) has already loaded the standard math module for any reason, then trying to load it again with import or __import__() will simply return a reference to the already-loaded module. You should be able to verify this using print id(math) and comparing with print id(command).

    Although you've stated that you are unable to change the name of math.py, I suggest you can. You are getting the name of the module to load from the user. You can modify this before actually using the __import__() function to add a prefix. For example:

    command = __import__("cmd_" + cstr)
    

    Then, rename math.py to cmd_math.py and you will avoid this conflict.

提交回复
热议问题