-1

I'm working in Flask and have split up the code into different files and note that some times I will import the same thing in two different files

Would it be a bad to have a separate Python file where you put all your imports then in all files that need some common libs just import that file?

I don't know if it might have consequences that I have not noticed.

imports.py

import os, requests, json 

some-file.py

from imports import *

Is this a bad idea?

davidism
  • 121,510
  • 29
  • 395
  • 339
norgia
  • 47
  • 1
  • 6
  • [Duplicate: How do imports work?](https://stackoverflow.com/q/10501724/1324033) – Sayse Jun 27 '19 at 13:31
  • 4
    To be honest, I wouldn't do that, I would just write it in all the files. But that's just my opinion. I think it makes it more intuitive to explicitly write it in every file. Performance-wise, there is no difference. – Finomnis Jun 27 '19 at 13:31
  • You would be letting your code more implicit than explicit. – Igor Servulo Jun 27 '19 at 13:32
  • 3
    **Yes.** Did you ever try to do `import this`? _Explicit is better than implicit._ Also, _simple is better than complex_. Avoid `from m import *` because `m` could shadow some names in the existing namespace. – Konstantin Sekeresh Jun 27 '19 at 13:36

1 Answers1

0

This answer (as pointed out by @Sayse) gives a good answer. However, to prevent beginners from missing that information. I'll also answer the question here.


As almost everyone has pointed out, don't do this.


First off as @Konstantin Sekeresh noted: explicit is better than implicit. Adding imports explicitly states what you're importing. In general don't do:

from ... import *

Because this hides what functionality comes from where.

Furthermore, it doesn't improve anything:

  • the duplicate code is not an issue, it's at the top of the file
  • it won't make your code faster

I also would not do:

import os, requests, json

Instead I would do:

import os
import requests
import json

Because it is much easier to read (especially when you have more than 3 imports)

Nathan
  • 3,558
  • 1
  • 18
  • 38