Python: import and change canonical names in the current module

In the Python package directory of my own creation, I have a __init__.py file that states:

 from _foo import * 

In the same directory there is _foomodule.so, which is loaded as above. The shared library is implemented in C ++ (using Boost Python). This allows me to say:

 import foo print foo.MyCppClass 

This works, but with a quirk: the class is known to Python in the full package path, which forces it to print this:

 foo._foo.MyCppClass 

So, although MyCppClass exists as an alias in foo , foo.MyCppClass not its canonical name. In addition to being a little ugly, it also makes help() little lame: help(foo) will say that foo contains the _foo module, and only if you say help(foo._foo) will you get documentation for MyCppClass .

Is there something I can do differently in __init__.py or otherwise make Python see foo.MyCppClass as a canonical name?

I am using Python 2.7; it would be great if the solution worked on 2.6 as well.

+4
source share
2 answers

I had the same problem. You can change the module name in the definition of Boost.Python:

 BOOST_PYTHON_MODULE(_foo) { scope().attr("__name__") = "foo"; ... } 

Help issue is a separate issue. I think you need to add each element in __all__ in order to get it for export.

When I do both of them, the name foo.MyCppClass is just that - foo.MyCppClass - and help(foo) provides documentation for MyCppClass .

+2
source

You can solve the help() problem by adding the line

 __all__ = ['MyCppClass'] 

into your __init__.py file.

+1
source

Source: https://habr.com/ru/post/1398281/


All Articles