Python - Doubt about imports in the creation of libraries

Asked

Viewed 49 times

0

If I’m creating a library, and I put in it import json, in my main (my main file) I would have to import the json or just import from my own library?

Thanks for your help.

1 answer

1


Need to import again:

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

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

When I run by 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 care again or not, there are some things we have to keep in mind:

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

#teste1.py
print ("Olá")

#teste2.py
import teste1
import teste1

When running teste2.py by the prompt, my output is:

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

Note that he only ran teste1.py once.

2) If you want to use multiple libraries in multiple files, you can do the Imports on __init__.py. See more about this here or here.

  • Thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.