Search code examples
pythonpython-3.xpython-class

Python - Import class function/method from main to use in another file


I have two files - main.py and uploadfile.py. Main.py (GUI) takes user input, and provides this to uploadfile.py to process. I have an entry from uploadfile import Uploader in main that allows main to talk to uploadfile.

I need to have error handling, and I need to call the errorfunc residing in main.py from uploadfile.py if there is an error (this is to display an alert window with the error in question).

main.py

class ErrorHandling (QDialog):
   def __init__(self, ErrorObject):
   QMessageBox.__init__(self)

   def errorfunction(self):
       print("error!")

uploadfile.py

class Uploder:
      def __init__(self):

      def uploadfile(self, item1frommain, item2frommain)
          for Files in self.Filestoupload:
              try:
                 self.FileCopy(FilePaths, Metadata)
              except Exception as errno:
                 errorfunction(errno) #<--- placeholder as unsure how to achieve

Apologies if this code is incomplete, main and uploadfile are rather large to post in entirety. I would be appreciative of just knowing the way in which I would do this (call a class method/function that is in main). Note, trying from main import ErrorHandling causes main to no longer run with the error cannot import name Uploader from uploadfile.


Solution

  • Adding any import statements(of main.py) at the top of uploader.py will cause circular import errors. Two ways to remedy it.

    1. Move ErrorHandling to a new utils.py module
    2. Write the import statement inside except clause
    try:
      self.FileCopy(FilePaths, Metadata)          
    except Exception as errno:
      from main import ErrorHandling
      ErrorHandling(errno)
      ...
      ...