Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23160

Stop a python package's import dependencies from showing up in an editor's tab completion?

$
0
0

I am developing a python package that heavily relies on a few dependencies: numpy, scipy, matplotlib, etc. I want to be able to use these dependencies within various files without having them show up via tab completion in a code editor when someone imports my package. For example, consider the most basic package with the file structure below.

\mypackage    __init__.py     mymodule.py

Let the __init__.py file be the following:

import numpy as npfrom . import mymodule 

In this case, when the user imports mypackage, I do not want .np to show up with the editor's tab completion. Instead, I only want .mymodule to show up. For example,

import mypackage as pkgpkg.<TAB> -> pkg.mymodule

I am already able to get the behavior that I described by doing two things, but they are not necessarily ideal. What I'm currently doing involves:

  1. Using underscores. For example, when I just need access to just a few classes or functions, I use an underscore alias:
from numpy import ndarray as _ndarray

I do not want to use this method when importing full packages though, e.g., import numpy as _np, because the extra underscores would clutter up the code base.

  1. Imports inside the function's scope. For example, consider the sample mymodule.py file shown below. The module only contains one function that relies on matplotlib. Rather than importing matplotlib at the top of the file, the import is done within the function's scope. Notice how I also included using the underscore approach from (1) to include type hints.
# mymodule.pyfrom numpy import ndarray as _ndarraydef plot(x: _ndarray, y: _ndarray) -> None:    import matplotlib.pyplot as plt    plt.plot(x, y)    plt.show()

Using (1) and (2), when mymodule is imported, the tab completion will only show plot, which is the behavior I want. However, this structure means that I have ALOT of numpy, scipy, etc. imports throughout my code. Significantly more than I would have if the imports were only at the top of each file. Luckily the imports are fast, so I have not been suffering from slow computational speeds, even for functions that are frequently called. So mainly, this is just an issue with code organization and style, but will become more and more important as this package continues to grow.

Hopefully there is a better way to manage getting this same behavior than what I've currently been doing. Please provide any suggestions and/or solutions you've come across or used in your own projects.

Thanks in advance!!


Viewing all articles
Browse latest Browse all 23160

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>