Reputation: 174
I actually don't have any question about my code but i use a ide named pycharm while running my code i don't get any error but my ide gives me a warning why is that so?
Here's my code :
def hi():
global d
d = 5
hi()
print(d)
My code works fine but my ide gives me a warning at line 2 of my code which is Global variable 'd' is undefined at the module level.
Did i do anything wrong in my code i just created a global variable through a function and accesed it outside the function.
does anyone know why this is happening?
Upvotes: 2
Views: 4177
Reputation: 41
If you just want to get rid of the warning "Global variable 'd' is undefined at the module level."
You could declare the desired global variable and don't not assign a value (None) with type hints.
d :str
d :str
def hi():
global d
d = 5
hi()
print(d)
Upvotes: 1
Reputation: 109
As you said there is no error, just a warning. You can look up the different inspection severity levels here
I quote from this website:
Warning: marks code fragments that might produce bugs or require enhancement.
So Pycharm is trying to tell you that using global in this way could lead to bugs down the line, especially if your code gets more complicated. This warning appears so that you get a change to rethink how your code works and that there are maybe better ways to achieve the same goal.
In this case the warning comes from the fact that d is undefined at the module level, which can be fixed by defining it, e.g. at the top.
d = 11
In general there are many reason why one should avoid the global keyword (see discussion here), but if you know why you are using it then its fine.
Upvotes: 3
Reputation: 528
Global variables are never recommended as they could produce errors in the future as see Why are global variables evil?
your code should be
def hi():
return 5
print(hi())
Upvotes: 2