betelgeuse
betelgeuse

Reputation: 459

Python module: how to prevent importing modules called by the new module

I am new in Python and I am creating a module to re-use some code. My module (impy.py) looks like this (it has one function so far)...

import numpy as np
def read_image(fname):
    ....

and it is stored in the following directory:

custom_modules/
              __init.py__
              impy.py

As you can see it uses the module numpy. The problem is that when I import it from another script, like this...

import custom_modules.impy as im

and I type im. I get the option of calling not only the function read_image() but also the module np.

How can I do to make it only available the functions I am writing in my module and not the modules that my module is calling (numpy in this case)?

Thank you very much for your help.

Upvotes: 7

Views: 2543

Answers (3)

Hannes Ovrén
Hannes Ovrén

Reputation: 21831

If you really want to hide it, then I suggest creating a new directory such that your structure looks like this:

custom_modules/
    __init__.py
    impy/
        __init__.py
        impy.py

and let the new impy/__init__.py contain

from impy import read_image

This way, you can control what ends up in the custom_modules.impy namespace.

Upvotes: 1

Joël
Joël

Reputation: 2812

I've got a proposition, that could maybe answer the following concern: "I do not want to mess class/module attributes with class/module imports". Because, Idle also proposes access to imported modules within a class or module.

This simply consists in taking the conventional name that coders normally don't want to access and IDE not to propose: name starting with underscore. This is also known as "weak « internal use » indicator", as described in PEP 8 / Naming styles.

class C(object):
    import numpy as _np  # <-- here
    def __init__(self):
        # whatever we need
    def do(self, arg):
        # something useful

Now, in Idle, auto-completion will only propose do function; imported module is not proposed.

By the way, you should change the title of your question: you do not want to avoid imports of your imported modules (that would make them unusable), so it should rather be "how to prevent IDE to show imported modules of an imported module" or something similar.

Upvotes: 2

danodonovan
danodonovan

Reputation: 20341

You could import numpy inside your function

def read_image(fname):
    import numpy as np
    ....

making it locally available to the read_image code, but not globally available.

Warning though, this might cause a performance hit (as numpy would be imported each time the code is run rather than just once on the initial import) - especially if you run read_image multiple times.

Upvotes: 1

Related Questions