Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to import a file named after a keyword in Python?

Imagine that there's a Python library states, in which there is a script for each of the 50 states, named after those state abbreviations.

al.py
ak.py
...
or.py
...
wi.py
wy.py

This certainly isn't the best way to structure code. But given that it exists, and given that or is a reserved keyword, is there a reasonable way to write a caller for Oregon that includes the statement

from states import or

Or does the library have to change their naming convention to something a bit better, like the full state name.

like image 405
Teddy Ward Avatar asked Aug 08 '18 20:08

Teddy Ward


1 Answers

You can't import or directly, even when doing from... import... as. Instead, you will need to use the function-based import mechanism supplied in importlib. This will work:

import importlib
_or = importlib.import_module('states.or')

and you can refer to the module as _or.

like image 131
Daniel Roseman Avatar answered Oct 06 '22 06:10

Daniel Roseman