skip to Main Content

I think i defined ‘api’ as twitter.api, idk why this error is happening
code:

 import twitter


def auth():                      
    api = twitter.Api(consumer_key='CsqkkrnhBZQMhGLpnkqGqOUOV',
    consumer_secret='jzbWgRLZqIyJQjfh572LgbtuifBtXw6jwm1V94oqcQCzJd7VAE',
    access_token_key='1300635453247361031-EWTTGf1B6T2GUqWmFwzLfvgni3PoVH',
    access_token_secret='U2GZsWT0TvL5U24BG9X4NDAb84t1BB059qdoyJgGqhWN4')
                                
auth()
api.PostUpdate('Hello World')

 

error:

Traceback (most recent call last):
  File "C:/Users/Xtrike/AppData/Local/Programs/Python/Python37/twitter python.py", line 11, in <module>
    api.PostUpdate('Hello World')
NameError: name 'api' is not defined

2

Answers


  1. For what you posted, you need to initiate api variable. It just get everything and do the PostUpdate, but first you need to instantiate it.

    Login or Signup to reply.
  2. You may need to learn about local and global scopes in Python. In short you’ve created a local variable api that is not visible outside of function.

    As of solving the provided error, there are different approaches depending on desired result:

    1. Use reserved word global to make variable visible at global scope:
    def auth():
        global api # This does the trick publishing variable in global scope
        api = twitter.Api(consumer_key='<>',
            consumer_secret='<>',
            access_token_key='<>',
            access_token_secret='<>')
                                    
    auth()
    api.PostUpdate('Hello World') # api variable actually published at global scope
    

    However I’d not recommend using global variables without proper conscise

    1. Provided code is small so no need to wrap into additional function
    api = twitter.Api(consumer_key='<>',
            consumer_secret='<>',
            access_token_key='<>',
            access_token_secret='<>')
                                    
    api.PostUpdate('Hello World')
    
    1. Returning object from function – I recommend this approach as most suitable and reliable
    def auth():                      
        api = twitter.Api(consumer_key='<>',
            consumer_secret='<>',
            access_token_key='<>',
            access_token_secret='<>')
        return api
                                    
    api = auth()
    api.PostUpdate('Hello World')
    

    Last, but important word: avoid publishing secrets in public posts – these are not needed for solution but may be exposed to wrecker.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search