2

I'm studying python, and getting struggle with the global keyword within vscode. So far the code is working, but the vscode linter is raising an error, and I would like to understand why

I've tried using the global keyword, and the code works fine even though I got a linter error. I try using a local variable and didn't get any error

def whatIs ():
    global myvalue
    myvalue +=10
    print("myvalue: {}".format(myvalue))

myvalue=10

whatIs()

print("myvalue: {}".format(myvalue))

The linter points to the myvalue in the function :

Undefined variable 'myvalue' pylint(undefined-variable)

But the output is what I expect.

myvalue: 20
myvalue: 20

It's like vscode doesn't like the global keyword

xashru
  • 3,400
  • 2
  • 17
  • 30
jmnguye
  • 347
  • 2
  • 9
  • 3
    The linter is checking the code from the top. When it checks the `whatIs` method, it doesn't know that a global variable `myvalue` __will__ be defined later on. – rdas May 12 '19 at 08:44
  • 3
    Why should you use `global` is the first question? You can pass argument and return the result in the simplest readable way. – Austin May 12 '19 at 08:46
  • 1
    `pylint` takes automatic exception to `global`. According to its rule you are never right to use it. That is only sort of true, and not all of the time. – BoarGules May 12 '19 at 08:58

2 Answers2

1

Try moving this line

myvalue=10

before the definition of WhatIs function.

myvalue=10

def whatIs ():
    global myvalue
    myvalue +=10
    print("myvalue: {}".format(myvalue))

whatIs()

print("myvalue: {}".format(myvalue))
Manu mathew
  • 859
  • 8
  • 25
1

It's considered bad practice to use Global variables in python. A simple fix is to save the function call as a variable like so.

def whatIs(myvalue):
    myvalue +=10
    print(myvalue)
    return myvalue

result = whatIs(10)
print(result)
buddemat
  • 4,552
  • 14
  • 29
  • 49
John Carr
  • 69
  • 3