1

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"

asked Jul 30, 2019 at 5:49

2 Answers 2

1

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
answered Jul 30, 2019 at 14:07
Sign up to request clarification or add additional context in comments.

Comments

0

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())
answered Jul 30, 2019 at 6:05

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.