简体   繁体   中英

How to locally import packages in python module

I use numpy for my customized functions stored in my module. Is it true that the package numpy will be automatically imported into the file in which I call my module? Can I make the package numpy only available for the function defined in my module but not the file which calls my module?

When you call import numpy in your module then, yes, it is only available within your module and not from whatever module happens to import yours. There is nothing stopping the outer module from importing numpy itself, though, as it must be installed on the system for you to import it yourself.

ETA:

Demonstration:

In inner.py :

import numpy as np
print ("Inner: ", np.__version__)

In outer.py :

import inner
print ("Outer: ", np.__version__)

Outputs:

$ python outer.py
('Inner: ', '1.9.2')
Traceback (most recent call last):
  File "outer.py", line 3, in <module>
    print ("Outer: ", np.__version__)
NameError: name 'np' is not defined

ETA:

This could happen if you imported your module with a wildcard ( from inner import * ). PEP8 discourages this :

Wildcard imports ( from <module> import * ) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM