Python: Importing a module with the same name as a function

For background: First time asking a question on SE. I'm still quite new at Python, and not very experienced with programming in general. I've searched around but I haven't found an answer to this question, and I'd greatly appreciate your help.

My question is: How can I import a module which has the same name as a function?

To be specific, I am working with the Python symbolic math library, sympy 0.7.5, using Python 2.7.

Sympy has a structure like this:

sympy
 |
 +-- __init__.py
 +-- simplify
       |
       +-- __init__.py
       +-- simplify.py
       |      |       
       |      +-- def simplify(...)
       |
       +-- fu.py
            |
            +-- def TR8(...)
            +-- def fu(...)

What I am looking to do is import fu.py from this structure, so that I can call the TR8 function. However, I'm not having much luck.

This works:

from sympy.simplify.fu import *

TR8(some_expression)

So far, this is the only way I am able to access TR8, but I know it's not the recommended way.

The following attempts fail:

from sympy.simplify import fu

fu.TR8(some_expression)
>>AttributeError: 'function' object has no attribute 'TR8'

from sympy import fu

fu.TR8(some_expression)
>>AttributeError: 'function' object has no attribute 'TR8'

I'm not certain, but it seems to me like Python thinks I'm trying to import the function called fu instead of the module called fu. Likewise, When I try it this way:

import sympy.simplify.fu as fu
>>AttributeError: 'function' object has no attribute 'fu'

Here Python seems to think I'm talking about the function sympy.simplify.simplify, instead of the module sympy.simplify.

So is there a proper way to ask Python to import a module, when that module contains a function with the same name as the module?


sympy/simplify/__init__.py contains the following line:

from .fu import FU, fu

This hides the fu module by assigning the fu function where you would expect the module to go, blocking most ways to import it.

If you just want the TR8 function, you can import that:

from sympy.simplify.fu import TR8

If you need the fu module, an entry remains in sys.modules :

import sympy.simplify.fu
import sys

fu_module = sys.modules['sympy.simplify.fu']

It's ugly, but it should work. As far as I know, this is the simplest way to get at the module itself.


You can also use a namespace for the module.

from simpy.simplify import fu as fu_module

That should work just fine.

链接地址: http://www.djcxy.com/p/78022.html

上一篇: Paypal Rest API的工作

下一篇: Python:导入与函数名称相同的模块