0
  1. Why am I able to call to and return variable (HTTP request) properties from this function without passing a parameter first?
  2. How does the f in f"abc123" work?
import requests

def oauth(r):
    r.headers["Authorization"] = f"abc123"
    r.headers["User-Agent"] = "v2TweetLookupPython"
    return r

my_json = requests.request("GET", url, auth=oauth).json()

The call to the oauth function in auth=oauth is successful, without having to pass its parameter, r. With the requests module, is the single character 'r' an implicit reference to a requests object?

otonomi
  • 3
  • 1

3 Answers3

1

Because you're not calling the function oauth, but just passing the object oauth as parameter to the optional argument auth of requests.request.

The requests.request itself calls the oauth when appropriate passing the r parameter. Look at what the documentation says about the optional parameter auth from requests.request:

Default Authentication tuple or object to attach to Request.

You only call a function when you use parenthesis at the end.

Nilton Moura
  • 313
  • 2
  • 8
0

auth is taking in a function as a parameter value.

This is allowed in Python, as functions are first-class. That function may be called somewhere in the requests package, but this is a detail that packages are meant to abstract away; all you need to know is that the auth parameter is given as a function that takes in one parameter.

The f refers to a format string -- but in this case, the f is redundant since there aren't any dynamically evaluated expressions to be placed inside the string.

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
0

1.) The requests.request function takes a function as its auth argument and evaluates the first argument of the function with a request. So, you pass your oauth function to requests.request function and it automatically evaluates this function with the request as the argument you call r.

You can see this if you just print r inside oauth when you run the code:

import requests

url = 'https://httpbin.org/get'

def oauth(r):
    print(f'r is {r} of type {type(r)}')
    r.headers["Authorization"] = f"abc123"
    r.headers["User-Agent"] = "v2TweetLookupPython"
    return r

my_json = requests.request("GET", url, auth=oauth).json()
print(my_json)

Note that I'm just using a test url here.

2.) A letter before a string modifies the type of string. So f'string' makes this a "formattable" string. For example, suppose I wanted a function that takes a string variable with a person's name and outputs a hello message based on that string variable. I could do something like:

def helloMessage(name):
    return f'Hello {name}, welcome.'

If I called helloMessage('Bob') it would return 'Hello Bob, welcome.'