Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import with dot name in python

Tags:

python

import

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.

like image 773
Persijn Avatar asked Nov 28 '14 12:11

Persijn


1 Answers

The situation is tricky, because dots mean subpackage structure to Python. Recommend to simply rename 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(module)
like image 61
wim Avatar answered Sep 29 '22 22:09

wim