2

I have the following code:

import json
import os
from botocore.vendored import requests
from custom_validator import CustomValidator

dev_mode = 'DEV' in os.environ
access_token = None

if dev_mode:
    import test_config as config
else:
    import config as config

def myfunc(data):
     if not (access_token):
         .....

But inside of myfunc, I get the Unresolved reference error when trying to use access_token. Even if I put global before it in the initialization above, I get:

Global variable 'access_token' is undefined in the module level

I'm kind of confused - why is this happening and how can I fix it?

Using Python 3.6.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Gambit2007
  • 3,260
  • 13
  • 46
  • 86
  • Please post the entire error message including stack trace. – deceze Dec 04 '18 at 15:29
  • That's everything.. i get that in PyCharm. – Gambit2007 Dec 04 '18 at 15:31
  • Code is correct, check what is inside imports, especially `config` – grapes Dec 04 '18 at 15:31
  • This is happening because of Python's LEGB variable scoping rules (https://stackoverflow.com/a/293097/4180458). You need to use `global access_token` statement before if condition. In order to access/modify a global variable inside a function, you need to tell Python that it's a global variable else it will raise an error `local variable 'access_token' referenced before assignment` or create a local variable (in case of assignment). – AimZ Jun 10 '20 at 20:02

0 Answers0