简体   繁体   中英

How to fix Attribute Error in importing files?

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Main\Programming\Python\Console\mod_project\auto_message_mod.py", line 5, in <module>
    import mod
  File "D:\Main\Programming\Python\Console\mod_project\mod.py", line 77, in <module>
    main()
  File "D:\Main\Programming\Python\Console\mod_project\mod.py", line 18, in main
    main_program_menu()
  File "D:\Main\Programming\Python\Console\mod_project\mod.py", line 36, in main_program_menu
    auto.auto_message_tools()
AttributeError: partially initialized module 'auto_message_mod' has no attribute 'auto_message_tools' (most likely due to a circular import)

I keep getting these errors while I try to import the file call auto_message_mod.py into mod.py and in mod.py , I tried to call the function auto_message_tools (these files are in the same folder). I also have imported the other files into mod.py and it worked perfectly. Except auto_message_mod.py . I have written import auto_message_mod as auto but it was not working. I have already tried auto.auto_message_tools() but didn't work. Can someone please help me?

Python is a scripting language, which is interpreted line by line. An import statement literally means that it will jump into that file and start reading over it, before jumping back to the original file and continuing to read through that. Read more here .

You can see that in your traceback, you import a file, which then calls a function that is presumably in the original.

The best way to fix this is to separate import-time code from run-time code. That means everything should import before the code is run, meaning all your code outside your main file should be only found within functions and classes. That means that you are much less likely to create a circular import like this, since all the code will already be initialised before you call any of it.

If that doesn't work, experimenting with moving culprit import statements to the bottom often helps, although it is stylistically bad, so I'd only use it as a last resort.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM