Home > Blockchain >  Python: How to import by name
Python: How to import by name

Time:05-04

if __name__ == "__main__":
  from SettingsHandler import YamlParser
  from UIComponents.IncrementSlider import IncrementSlider
  from UIComponents.ToggleSwitch import ToggleSwitch
  from UI.SettingsPane import SettingsPane
  #from KeyStrokeWrapper import KeyStrokeWrapper
else:
  from Handlers.SettingsHandler import YamlParser
  from Handlers.KeyStrokeWrapper import KeyStrokeWrapper
  from Handlers.UIComponents.IncrementSlider import IncrementSlider
  from Handlers.UIComponents.ToggleSwitch import ToggleSwitch
  from Handlers.UI.SettingsPane import SettingsPane

This is starting to get rediculous, how do I import by only file name?

eg: import IncrementSlider rather than from Handlers.UIComponents.IncrementSlider import IncrementSlider

CodePudding user response:

You can simply say "import X", where X is that file name, and from there if you have to refer to specific things, just say "X.YYY", where Y is that specific thing. You do this when you say "from Handlers.SettingsHandler import YamlParser". Make sure that if you import a folder, that folder has an "init.py" file there. Let me know how that works!

CodePudding user response:

This is not much of an answer or a solution, rather a similar situation that I had.

I've had a similar problem with scrapy framework, where I repeated from x import like 7 times. I solved that by changing the PYTHONPATH environment variable to point to the directory where the modules were, but be careful! Because when I did that scrapy couldn't see its options.py file (which is not explicitly imported) so I had to change some variables related to scrapy from the shell.

Google how to change the PYTHONPATH environment variable for your OS. I would also recommend using a virtual environment before doing that, to avoid messing your python system-wide.

  • Related