Python - Doubt about imports in creating libraries

0

If I'm creating a library, and I put import json , in my main (my main file) would I have to import json or just give import from my same library?

Thanks in advance for your help.

    
asked by anonymous 07.09.2018 / 16:50

1 answer

1

You need to import again:

#arquivo teste1.py
import random
print ("Olá")

#arquivo teste2.py
import teste8
for i in range(0,5):
    print(random.randint(0,i))

When I run through the prompt:

C:\Users\user_name\Desktop> python teste2.py
Olá
Traceback (most recent call kast):
  File "teste2.py", line 3, in (module)
    print(random.randint(0,i))
NameError: name 'random' is not defined

Whether you need to import again or not, there are a few things to keep in mind:

1) A library is never imported twice. If it has already been imported, it will not be loaded again.

#teste1.py
print ("Olá")

#teste2.py
import teste1
import teste1

When running test2.py from the prompt, my output is:

C:\Users\user_name\Desktop> python teste2.py
Olá

Note that it only ran test1.py once.

2) If you want to use multiple identical libraries in multiple files, you can make imports in __init__.py . See more about this here > or here .

    
07.09.2018 / 18:24