
Dear docs team, The code in the section "Approximating importlib.import_module()" [ https://docs.python.org/3/library/importlib.html#approximating-importlib-imp...] has an error. It seems that if, for, else should not be all aligned at the same level, unless there is a new syntax of Python that I do not know. Best, Chris

Hi Chris,
It seems that if, for, else should not be all aligned at the same level, unless there is a new syntax of Python that I do not know.
I'm happy to tell you it's a Python syntax you don't know ☺ The for-else structure reads as "The for searches for something, if the thing is found there's no need to search more, use `break`, if the thing is not found execute the else". In other words the else is executed if no `break` were executed. So in the doc: for finder in sys.meta_path: spec = finder.find_spec(absolute_name, path) if spec is not None: break else: msg = f'No module named {absolute_name!r}' raise ModuleNotFoundError(msg, name=absolute_name) it reads: Search for the module in sys.meta_path (stopping the search as soon as a module is found), but if the module is not found raise an exception. It's the proper way to write the good old: module_found = False for finder in sys.meta_path: spec = finder.find_spec(absolute_name, path) if spec is not None: module_found = True break if not module_found: msg = f'No module named {absolute_name!r}' raise ModuleNotFoundError(msg, name=absolute_name) Bests, -- Julien Palard https://mdk.fr

Hi Chris,
It seems that if, for, else should not be all aligned at the same level, unless there is a new syntax of Python that I do not know.
I'm happy to tell you it's a Python syntax you don't know ☺ The for-else structure reads as "The for searches for something, if the thing is found there's no need to search more, use `break`, if the thing is not found execute the else". In other words the else is executed if no `break` were executed. So in the doc: for finder in sys.meta_path: spec = finder.find_spec(absolute_name, path) if spec is not None: break else: msg = f'No module named {absolute_name!r}' raise ModuleNotFoundError(msg, name=absolute_name) it reads: Search for the module in sys.meta_path (stopping the search as soon as a module is found), but if the module is not found raise an exception. It's the proper way to write the good old: module_found = False for finder in sys.meta_path: spec = finder.find_spec(absolute_name, path) if spec is not None: module_found = True break if not module_found: msg = f'No module named {absolute_name!r}' raise ModuleNotFoundError(msg, name=absolute_name) Bests, -- Julien Palard https://mdk.fr
participants (2)
-
Chris Gu
-
Julien Palard