So I am trying to use a variable that is inside a function in another function.
One of them is the "message.py" file, that is in the folder "properties". The file looks like this:
def nachricht():
global msg
msg = input("Type: ")
return msg
The other file is the "badwords_check.py", that is in the folder "module". This file looks like this:
from properties.message import msg
from properties.badwords import BadWords
def badwords_check():
if any(word in msg for word in BadWords):
print("Dont use that word!")
else:
print("Message send!")
The problem now, is that I can't import "msg" from "message.py".
The error code looks like this:
from properties.message import msg
ImportError: cannot import name 'msg' from 'properties.message'
I had tried things like: Global, with/without function(without the function it works, but I need it with a function because some other code and files) and I tried return.
CodePudding user response:
You need to declare the global variable outside the function at the top and then you can modify it inside your function using global msg
.
msg= ''
def nachricht():
global msg
msg = input("Type: ")
return msg
CodePudding user response:
To add on to Vaibhav's answer, the function nachricht()
is never being called in badwords_check.py.
Hence, there is no input being taken and the variable msg also doesn't exist.
While declaring msg as a global variable, the function should also be called.
from properties.message import *
from properties.badwords import BadWords
#use nachricht()
#then use the below function
def badwords_check():
if any(word in msg for word in BadWords):
print("Dont use that word!")
else:
print("Message send!")
If nachricht()
is not used, then msg
will simply be a empty string.