Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 327
betelgeuse Avatar asked Nov 27 '13 12:11

betelgeuse


1 Answers

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.

like image 156
Joël Avatar answered Sep 27 '22 17:09

Joël