[Python-ideas] Idea: Importing from arbitrary filenames

Terry Reedy tjreedy at udel.edu
Sat Apr 14 15:26:52 EDT 2018


On 4/13/2018 11:28 PM, Ken Hilton wrote:
> Hi all,
> 
> First of all, please excuse me if I'm presenting this idea in the wrong 
> way or at the wrong time - I'm new to this mailing list and haven't seen 
> anyone propose a new idea on it yet, so I don't know the customs.
> 
> I have an idea for importing files with arbitrary names. Currently, the 
> "official" 

Alex Martelli intentionally put that in quotes.

> way to import arbitrary files is to use the "imp" module, as 
> shown by this answer: https://stackoverflow.com/a/3137914/6605349

Read the first comment -- the above is deprecated.  There was always the 
__import__(name) function, but importlib.import_module is recommended now.

> However, this method takes two function calls and is not as 
> (aesthetically pleasing? is that the word?) as a simple "import" statement.

Only one is needed for most purposes.  importlib has separate find and 
load functions, which are used by 'import', and which are available to 
those who need them.

> Second, importing with a string literal specifying the path to a file:
> 
>      import '/home/pi/anti-gravity.py' *as antigravity*

antigravity = import_module('/home/pi/anti-gravity.py')

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list