I have a variable "OTPN" in an otp_fun file and I want to import that variable to the Main file, I tried by importing "From otp_fun import otpn", But it is throwing an error
otp_fun file code
def otp():
new = int(random.random()*1000000)
global otpn
otpn = round(new,6)
main file code
from Contacts.otp_fun import otp,otpn
it has to import otpn variable but it is throwing an error saying " ImportError: cannot import name 'otpn' from 'Contacts.otp_fun"
2 Answers 2
You cannot import otpn because it has not been defined, you see it is defined in otp, but this variable will only be made available after calling it.
You may think a solution would be to define otpn in global scope with a default value like this:
otp_fun file code
otpn = None
def otp():
new = int(random.random()*1000000)
global otpn
otpn = round(new,6)
But if you import it using from Contacts.otp_fun import otpn and then call otp you will see the value does not change :(
main file code
from otp_fun import otpn, otp
print(otpn)
# prints None
otp()
print(otpn)
# prints None
To keep the value linked you want to import the whole module with import Contacts.otp_fun.
main file code
import otp_fun
print(otp_fun.otpn)
# prints None
otp_fun.otp()
# changes otpn value
print(otp_fun.otpn)
# prints some random number
Comments
you can use Class:
otp_fun file code :
import random
class Otp():
def otp(self):
new = int(random.random() * 1000000)
global otpn
otpn = round(new, 6)
return otpn
main file code:
from Contacts.otp_fun import Otp
myVariable = Otp()
print(myVariable.otp())