0

I have read this post, and it is very helpful. How to import the class within the same directory or sub directory?

However, in Python3, it requires a dot if an import is in the same directory. This makes the whole point (of importing both from same and sub directory) meaningless.

Only one of these two works, based on where the script is called:

from some_class import * # calling within the same directory

or

from .some_class import * # calling from somewhere else, as part of a module

I want the script to be called in the folder and as a part of a module, and have a dirty solution as follows:

try:
    from some_class import *
except:
    from .some_class import *

Are there any better solution, the best one statement ones?

xxbidiao
  • 834
  • 5
  • 14
  • 27
  • [`from __future__ import absolute_import`](https://www.python.org/dev/peps/pep-0328/)? – Aran-Fey Jul 02 '18 at 21:35
  • @Aran-Fey No. That is already default in 2.7. – wim Jul 02 '18 at 21:35
  • 5
    Then I have no idea what the question is. – Aran-Fey Jul 02 '18 at 21:36
  • There is no better solution. – Mad Physicist Jul 02 '18 at 21:49
  • Edited the question to clarify that I want to use the script in both scenarios. – xxbidiao Jul 02 '18 at 21:53
  • 2
    Disagree. The better solution is, don't use import from same directory at all (this is implicit relative import, avoid it). The second form shown here can and should work correctly for both cases, if you set up the package structure correctly. – wim Jul 02 '18 at 21:55
  • Like wim said, you should separate executable code from library code. `some_class` is library code. – Aran-Fey Jul 02 '18 at 22:20
  • @Aran-Fey Thanks for the advice. I'm actually trying to turn this into a library code but want legacy code to run in the same directory too. – xxbidiao Jul 02 '18 at 22:23
  • 1
    @xxbidiao fyi, you can treat local code as library code if it is installed as a package, in which case you can have the same import statements no matter where you are. You can emulate this behavior during development by working with [an editable install](https://stackoverflow.com/questions/35064426/when-would-be-e-editable-option-useful-with-pip-install?lq=1) of your code. – Arne Jul 02 '18 at 22:28

0 Answers0