Python Forum

Full Version: Calls to Attributes of a Class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
how does a direct call to openpyxl.load_workbook work?

According to OpenPyXL documentation, load_workbook is a submodule of a the subpackage reader i.e:
openpyxl.reader.excel.load_workbook

However a direct call to openpyxl.load_workbook works fine while using other submodules of openpyxl need the full callout. See below:

Initially in my code I had:
import openpyxl
try:
    openpyxl.load_workbook(filename)
except openpyxl.InvalidFileException as ife:
    print(ife)
which gave me the following error:
Error:
except openpyxl.InvalidFileException as ife: AttributeError: module 'openpyxl' has no attribute 'InvalidFileException'
however, when I changed line 4 to:
except openpyxl.utils.exceptions.InvalidFileException as ife:
exception handling work without an error.

Why full Callout required on one and not the other submodule? I could not find anything in the Documentation.
it depends what names are available on top level

>>> import openpyxl
>>> dir(openpyxl)
['DEFUSEDXML', 'LXML', 'NUMPY', 'Workbook', '__author__', '__author_email__', '__builtins__', '__cached__', '__doc__', '__file__', 
'__license__', '__loader__', '__maintainer_email__', '__name__', '__package__', '__path__', '__spec__', '__url__', 
'__version__', '_constants', 'cell', 'chart', 'chartsheet', 'comments', 'compat', 
'constants', 'descriptors', 'drawing', 'formatting', 'formula', 'load_workbook', 
'open', 'packaging', 'pivot', 'reader', 'styles', 'utils', 'workbook', 'worksheet', 'writer', 'xml']
load_workbook is made available/is exposed on top level

Here is the __init__.py source code
https://foss.heptapod.net/openpyxl/openp..._init__.py

In other words - it's a decision of the developer how to organise their code and what names to be exposed top level.
Also, note that open is alias for load_workbook
Thanks buran. Exactly what I was looking for. Thumbs Up