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

For the background: the first time we ask a question on SE. I'm still new to Python and not very good at programming in general. I searched, but I did not find the answer to this question, and I would really appreciate your help.

My question is: how to import a module with the same name as a function?

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

Sympy has this structure:

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

What I want to do is import fu.py from this structure so that I can call the TR8 function. However, I’m out of luck.

It works:

 from sympy.simplify.fu import * TR8(some_expression) 

This is still the only way to access the TR8, but I know that this is not recommended.

The following attempts are made:

 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 sure, but it seems to me that Python thinks I'm trying to import a fu function instead of a module named fu. Similarly, when I try it like this:

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

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

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

+7
python
source share
2 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 expect the module to work, blocking most of its import methods.

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

 from sympy.simplify.fu import TR8 

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

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

This is ugly, but it should work. As far as I know, this is the easiest way to access the module itself.

+3
source share

You can also use the namespace for the module.

 from simpy.simplify import fu as fu_module 

This should work fine.

0
source share

All Articles