Can not import a class from another file in the same directory in Python

Can not import a class from another file in the same directory in Python



I am quite new to Python and I am still getting used to it. I have a project which was written by using a bunch of files containing only function definitions. I decided to remake it in OOP paradigm so this is what happens:



Back then, I had these two files:


Main
| ---- loggingManager.py
| ---- servoManager.py



in the servoManager.py script I had:


from loggingManager import *
...
from time import sleep



and it all works fine. I can use all of the functions defined in loggingManager.py without any issues.



Now I have it like this:


Main
| ---- Logger.py
| ---- ConfigurationWrapper.py



The content of the ConfigurationWrapper is :


import configparser

class ConfigurationWrapper:
default_path = '/home/pi/Desktop/Bree/config.ini'

def __init__(self, path_to_file=None):
if path_to_file is None:
path_to_file = self.default_path
...



and Logger looks like this:


class Singleton(type):
_instances =
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwarg$
else:
cls._instances[cls].__init__(*args, **kwargs)

return cls._instances[cls]

class Logger():
__metaclass__ = Singleton



My goal here is to import:


import ConfigurationWrapper



in Logger.py script file but every time I do that, I get an error (by typing 'python Logger' in the terminal on MacOS):


Traceback (most recent call last):
File "Logger", line 1, in <module>
import ConfigurationWrapper
ImportError: No module named ConfigurationWrapper



I tried to add empty __ init __.py file in the same folder but still nothing happens.




2 Answers
2



Try adding a dot (.) before the imported module



import .ConfigurationWrapper


import .ConfigurationWrapper



or import your class



from .ConfigurationWrapper import ConfigurationWrapper


from .ConfigurationWrapper import ConfigurationWrapper



The dot (.) means that you're importing from the same directory.





Both of these are not working. I the first case I get 'invalid syntax' on the dot and in the second case 'Attempted relative import in non-package'.
– user2128702
Aug 27 at 21:06



The way I solved it was to add:


execfile("./ConfigurationWrapper")



but I'd like to know how appropriate is that.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.