2

If I have python...

r = requests.get('https://api.github.com/user', auth=('user', 'pass'))

How can I get it to work with...

myvar = 'get'
r = requests.myvar('https://api.github.com/user', auth=('user', 'pass'))

I.e. parse the string through as a command?

4 Answers 4

4

Use getattr:

myvar = 'get'
getattr(requests, myvar)('https://api.github.com/user', auth=('user', 'pass'))
Sign up to request clarification or add additional context in comments.

4 Comments

Ah thank you, attribute, not operator! I'll update the question and mark it as correct when I'm allowed.
Would r = self.requests.get('https://api.github.com/user', auth=('user', 'pass')) be getattr(self, requests, myvar)('https://api.github.com/user', auth=('user', 'pass'))?
@square_eyes Just replace getattr(self, requests, myvar) with getattr(self.requests, myvar) and the rest is identical.
Thanks again. Very quick and helpful.
0

getattr() will work perfectly, but it also means that a user can specify whatever method they choose, possibly ones you don't want to expose. Another approach would be:

{
    "get": requests.get,
    "post": requests.post, # maybe
    # etc
}[myvar]('https://api.github.com/user', auth=('user', 'pass'))

Comments

0

You can use getattr, https://docs.python.org/2/library/functions.html#getattr

r = getattr(requests, myvar)('https://api.github.com/user', auth=('user', 'pass'))

Comments

0

OK off the top of my head

myvar = 'get'
getattr(requests, myvar)('https://api.github.com/user', auth=('user', 'pass'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.