2

In Python 3.7 I would like to import few methos and use them later in the same script. Before that I would like to check if they are correctly imported.

Based on this answer I can check if a module is fully imported into the script but how if I imported only one method with the form from X import Y?

What I have done

I have done the following snippet:

from shapely.geometry import asShape
from shapely.geometry import Point
import sys

if 'shapely.geometry.asshape' in sys.modules:
  print('Shapely Geometry asshape ok')
else:
  print('Shapely Geometry asshape NOT loaded')
  
if 'shapely.geometry.point' in sys.modules:
  print('Shapely Geometry point ok')
else:
  print('Shapely Geometry point NOT loaded')

which gives me the following results:

Shapely Geometry asshape NOT loaded

Shapely Geometry point ok

Duplicate question

I don't this this is a duplicate question as all other questions here on SO are about check if a module is imported (with the form import Z) and not only some methods.

Community
  • 1
  • 1
Nicolaesse
  • 2,554
  • 12
  • 46
  • 71
  • If you import a name from a module in Python, the module is interpreted, stored in `sys.modules` and the name is referenced from that module into your import namespace. If you import an other name from the same module it is reuse from `sys.modules` and a new reference is created only. – Klaus D. Jan 17 '19 at 07:56
  • You don't have to check if a name is "correctly imported" - an import either succeed or raises an ImportError. Also, 'Point' is a class (not a module) defined in `shapely.geometry.point` (and imported by shapely.geometry cf https://github.com/Toblerity/Shapely/blob/master/shapely/geometry/__init__.py, which is why you find 'shapely.geometry.point' in sys.modules), and ` asShape` is a function defined in `shapely.geometry.geo` - there's no `shapely.geometry.asshape` _module_ so of course you won't find it in sys.modules. – bruno desthuilliers Jan 17 '19 at 08:48

2 Answers2

2

The built-in function dir() will give you a list which includes all imports. Your locally imported functions will appear there as well. You can check using:

'myFunction' in dir ()
1

It doesn't matter whether you import just one function from a module, or import the whole module itself, whole module is always imported into sys.modules. So, in your case, you'll have to check for imported module instead of the function:

'shapely.geometry' in sys.modules

Check out this qustion 'import module' vs. 'from module import function'.

Ahmad Khan
  • 2,655
  • 19
  • 25