0

I have a restful variable that I want to set to a global variable in python.

This code works. It allows the rest of the script to read the_api global the_api

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
the_api = tweepy.API(auth)
print(the_api)

This code does set the_api, but in other functions the_api is undefined... Why can't I vset the_api from within a function in python.

def initTweepy():
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    the_api = tweepy.API(auth)
    print(the_api)
jakeinmn
  • 167
  • 1
  • 3
  • 13
  • 1
    You can always read globals out of scope, but you must precede any assignment of the variable with `global [my_var]` if you want your changes to be effective outside of the current scope. – Alexander Sep 12 '15 at 19:34

1 Answers1

1

You need to use the global keyword otherwise python will create a new local variable shadowing the global variable.

def initTweepy():
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    global the_api
    the_api = tweepy.API(auth)
    print(the_api)
Ciaran Liedeman
  • 779
  • 5
  • 13