LGenzelis
LGenzelis

Reputation: 834

Python import warning

Let's say I want to use scipy in my program, giving it the alias sp. I also want to use the linalg module from scipy. Unlike what happens with numpy, the module is not automatically imported. So I have to write:

import scipy as sp
import scipy.linalg

This achieves the desired result: I can now write sp.linalg.inv(...).

The problem is that the line import scipy.linalg also imports scipy. And given that all my calls to scipy are made using the alias sp, spyder gives me the warning 'scipy' imported but unused in the second line.

What would be the right way of doing this? Or is mine the right way and the problem is just spyder's?

I could do:

import scipy.linalg
sp = scipy

But that doesn't look really pythonic..

Upvotes: 1

Views: 1542

Answers (1)

unutbu
unutbu

Reputation: 879451

If you use

from scipy import linalg

then scipy will not be added to the global namespace, though this will add linalg to the global namespace.


As a technical note, it is possible to define sp.linspace without adding scipy or linspace to globals:

import importlib
import scipy as sp
sp.linalg = importlib.import_module('scipy.linalg')

Note only sp is in globals():

print(globals().keys())
# ['__builtins__', '__file__', 'sp', '__package__', '__name__', '__doc__']

Or, alternatively,

import scipy as sp
sp.linalg = __import__('scipy.linalg', fromlist=['linalg'])

Upvotes: 1

Related Questions