Guest User

Untitled

a guest
Jan 24th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. TL;DR: you can't do relative imports from the file you execute since __main__ module is not a part of a package.
  2.  
  3. Absolute imports - import something available on sys.path
  4.  
  5. Relative imports - import something relative to the current module, must be a part of a package
  6.  
  7. If you're running both variants in exactly the same way, one of them should work. Anyway, here is an example that should help you understand what's going on, let's add another main.py file with the overall directory structure like this:
  8.  
  9. ```
  10. .
  11. ./main.py
  12. ./ryan/__init__.py
  13. ./ryan/config.py
  14. ./ryan/test.py
  15. ```
  16.  
  17. And let's update test.py to see what's going on:
  18.  
  19. ```
  20. # config.py
  21. debug = True
  22.  
  23.  
  24. # test.py
  25. print(__name__)
  26.  
  27. try:
  28. # Trying to find module in the parent package
  29. from . import config
  30. print(config.debug)
  31. del config
  32. except ImportError:
  33. print('Relative import failed')
  34.  
  35. try:
  36. # Trying to find module on sys.path
  37. import config
  38. print(config.debug)
  39. except ModuleNotFoundError:
  40. print('Absolute import failed')
  41.  
  42.  
  43. # main.py
  44. import ryan.test
  45. Let's run test.py first:
  46. ```
  47.  
  48. ```
  49. $ python ryan/test.py
  50. __main__
  51. Relative import failed
  52. True
  53. ```
  54. Here "test" is the __main__ module and doesn't know anything about belonging to a package. However import config should work, since the ryan folder will be added to sys.path.
  55.  
  56. Let's run main.py instead:
  57.  
  58. ```
  59. $ python main.py
  60. ryan.test
  61. True
  62. Absolute import failed
  63. ```
  64. And here test is inside of the "ryan" package and can perform relative imports. import config fails since implicit relative imports are not allowed in Python 3.
Add Comment
Please, Sign In to add comment