Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I import python class from a module located within file directory named '@file_directory' or directory with special characters?

I'm trying to import a class from a module named my_classes.py. Problem is, it's located within a directory called @file_directory.

So the structure is, I have main.py at the top of the project directory, and also a directory called lib at the same level. Within 'lib' there is subdirectory named '@file_directory' and within it a module 'my_classes' as shown below.

-> main.py
-> /lib
   -> lib_other_files.py
   -> /@file_directory
      -> my_classes.py

What I can usually do is

from lib.@file_directory.myclasses import cust_class

But because the @ symbol is a wrapper symbol, it prevents me from importing files from '@file_directory'. The simple soultion is of course, just change the directory name but I want to keep the file name/don't have the rights to change it in the project. Is there a way to use like a escpae character to import module from a directory with special characters?

like image 693
John Doenut Avatar asked Nov 06 '22 21:11

John Doenut


1 Answers

Another possibility: use the __import__() built-in function. This is essentially removing the overhead of the normal import command, but it allows you more flexibility in package-naming because it just takes a string as an argument - and that string can escape the otherwise-invalid characters.

So, this code should work:

_temp = __import__("lib.@file_directory.myclasses", globals(), locals(), ['cust_class'], 0)
cust_class = _temp.cust_class

Edit: The python standard library recommends using importlib instead. The same code would look like this in that:

import importlib
cust_class = importlib.import_module("lib.@file_directory.myclasses", "cust_class")
like image 52
Green Cloak Guy Avatar answered Nov 15 '22 11:11

Green Cloak Guy