Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 578
jbay Avatar asked Mar 13 '14 09:03

jbay


1 Answers

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.

like image 145
user2357112 supports Monica Avatar answered Sep 28 '22 03:09

user2357112 supports Monica