Import with dot name in python

Question:

How can I import a dotted name file in python?

I don’t mean a relative path, but a filename starting or containing a dot "."

For example: '.test.py' is the filename.

import .test will search for a test package with a py module in a parent package.

Asked By: Persijn

||

Answers:

The situation is tricky, because dots mean sub-package structure to Python. I recommend simply renaming your modules instead, if that’s an option!

However, importing a source file directly is still possible:

Python 2

Using imp:

import imp
my_module = imp.load_source("my_module", ".test.py")

Python 3

The imp module is deprecated in favour of importlib and slated for removal in Python 3.12. Here is a Python 3 replacement:

import importlib.util 
    
spec = importlib.util.spec_from_file_location(
    name="my_module",  # note that ".test" is not a valid module name
    location="/path/to/.test.py",
)
my_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(my_module)
Answered By: wim
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.