Home > Software engineering >  How to exclude objects when importing a python module
How to exclude objects when importing a python module

Time:12-29

Suppose this package which contains only one module:

mypackage/
    __init__.py
    mymodule.py

The __init__.py file is empty. The module mymodule.py is as follows:

from math import pi

def two_pi():
    return 2 * pi

This is the content of mymodule:

>>> from mypackage import mymodule
>>> dir(mymodule)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'pi', 'two_pi']

The object pi is present when I import the module, but I don't want it to be there.

How can I avoid pi from being present in mymodule?

I have tried defining __all__ = ['tow_pi'], however this only works when importing with from mypackage.mymodule import *.

CodePudding user response:

There is no way to hide pi from mymodule because it is simply part of the module's global namespace, an attribute of the module object.

A workaround is to import pi locally instead in mymodule.py:

def two_pi():
    from math import pi
    return 2 * pi

CodePudding user response:

I don't see why you would want to do that, since removing pi from mymodule will cause two_pi() not to work. Anyhow, you can use del(mymodule.pi) to remove the object pi from mymodule.

You might want to pass pi as a parameter to the function, and of course you can do from mymodule import two_pi

CodePudding user response:

You may use two files like: two_pi.py and __two_pi_impl.py

__two_pi_impl.py:

from math import pi as __pi

def two_pi():
    return 2 * __pi

two_pi.py:

import __two_pi_impl

two_pi = __two_pi_impl.two_pi

Then:

>>> import two_pi
>>> dir(two_pi)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__two_pi_impl', 'two_pi']
  • Related