Dan_Patterson

What is standard and not ... in python

Blog Post created by Dan_Patterson Champion on Jan 16, 2016

Some more information on finding python, its modules and whether they are built-in, modules of the standard distribution or those in the site-packages folder

References:

  29.12. inspect — Inspect live objects — Python 3.4.4 documentation look at the table on Types and Members

  http://stackoverflow.com/questions/247770/retrieving-python-module-path just one of hundreds of examples.

 

TypeAttributeDescription
module__doc__documentation string
__file__filename (missing for built-in modules)

 

TipsExample

A standard installation compatible with ArcMap and arcpy is assumed.

These:

  • dir(module_name)
  • help(module_name)

are your friends.

 

Look for a __file__ property in the function/property list.

The os module does...

>>> import  os
>>> dir(os)
[ ... snip ... '__doc__', '__file__',
'__loader__', '__name__', ... snip ... ]
>>> os.__file__
'C:\\Python34\\lib\\os.py'
>>>

 

The time module doesn't

>>> import time
>>> dir(time)
[ ... snip ... '__doc__', '__file__',
'__loader__', '__name__', ... snip ... ]
>>> time.__file__   # I will try anyway
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'module' object has no attribute '__file__'

Modules in the

C:\PythonXX\lib\

folder will have a __file__ property.

 

>>> # from ... C:\Python34\Lib   ... folder
>>> import collections
>>> collections.__file__
'C:\\Python34\\lib\\collections\\__init__.py'
Modules that aren't part of the standard distribution and have to be installed via pip or other means, get put in the site-packages folder and they will have a __file__

How about arcpy?

>>> import arcpy
>>> arcpy.__file__
'C:\\Program Files\\ArcGIS\\Pro\\Resources\\ArcPy\\arcpy\\__init__.py'
>>>

 

And my fav...

>>> import numpy as np
>>> np.__file__
'C:\\Python34\\lib\\site-packages\\numpy\\__init__.py'
You can use the inspect module as well... all the cool programmers do ...

Numpy was previously imported as np.

Notice the results are the same as the np.__file__ approach.

>>> import inspect
>>> inspect.getfile(np)
'C:\\Python34\\lib\\site-packages\\numpy\\__init__.py'
>>>

 

Lets try time.

>>> inspect.getfile(time)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python34\lib\inspect.py", line 518, in getfile
    raise TypeError('{!r} is a built-in module'.format(object))
TypeError: <module 'time' (built-in)> is a built-in module
>>>

No... it is a built-in.

But... you can another way...

>>> import time
>>> inspect.getmodule(time)
<module 'time' (built-in)>
>>>

Outcomes