2

I'm writing my own module mymodule. It contains this:

myroot
|-mymodule
| |-file1
| |-file2
|
|-tests
| |-...
|
|-...

In file1 I want to import file2. First I used from . import file2 because this seems to be best-practice – because there will be no trouble if I make a mistake at namespacing (for example when that file2 has I name that is already used or something like this, and it is also better if I want to import files from submodules).


Then I changed to use only import file2 because the tests have trouble with these relative imports. I have already described that problem here.


And now there are problems with the import without the . because they don't work anymore when the module is installed. (I installed it to my own computer.)


What is better? How do I avoid problems that could be triggered by the imports without .? (I know, I can take care about not to use names that are already used. But I can hardly believe something that might make someone elses program crash because he used my module.

So: what is best practice? And why? And if there isn't something like this: what to use where?

Community
  • 1
  • 1
Asqiir
  • 607
  • 1
  • 8
  • 23

1 Answers1

-1

Here is the difference between the two explained.

That means, different ways of importing the single parts of the script are needed when they are run in different ways.

That means what I have to do is not to decide which way of importing I should use but to use something like that:

if is_run_as_unittest:
  import file2
else:
  from . import file2

So I have to know whether it's a unittest or not. (I just assume this works also if the script is importet from a unittest, at least the most important thing is whether the main script (or top-level-module, whatever) is run as unittest or not.

Asqiir
  • 607
  • 1
  • 8
  • 23