Home > database >  Is it possible to import from two files with the same name?
Is it possible to import from two files with the same name?

Time:10-11

I have these files:

/somewhere/file.py
/elsewhere/file.py
/completeley/different/place/main.py

Now, within main.py I need stuff from the other files, in pseudocode:

from "/somewhere/file.py" import function_1
from "/elsewhere/file.py" import function_2

Can Python handle this? How?

Note that the trick of placing the empty __init__.py file cannot be used here (or at least I don't know how, also don't want to convert the whole file system into a Python package), and using sys.path.insert also fails because the two files have the same name.

CodePudding user response:

This should work.

from somewhere.file import function_1
from somewhere_else.file import function_2

If you want to import the modules

import somewhere.file as file_a
import somewhere_else.file as file_b

CodePudding user response:

Directories in python are indexed using a dot . so you would, and more important than that, the directories names should be written outside of quotes ". As per the answer given by Mat, you should do something like:

import somewhere.file as file_a
import somewhere_else.file as file_b
  • Related