'how can I keep the original reference to a function in python

According to set source ipv4 address in urllib3, I try to use below code snippet to set the source IP in a HTTP request:

    def bind_ip(source_ip):
        real_create_conn = urllib3.util.connection.create_connection
   
        def set_src_addr(address, timeout, *args, **kw):
            source_address = (source_ip, 0)
            return real_create_conn(address, timeout=timeout, source_address=source_address)
    
        urllib3.util.connection.create_connection = set_src_addr

    while url != null and ip != null:
        bind_ip(ip)
        r = requests.get(url)
    

But the server has multiple IPs, and I have to switch between them for my situation.

It works well for the first call. if calling this snippet repeatedly, things got wild.

for the second call and after, the value of "real_create_conn" is not the original implementation, but the "set_src_addr" function, which is assigned to "urllib3.util.connection.create_connection" in the later part. and it result in a "set_src_addr" chain as below picture:

enter image description here

I also tried to save the original "create_connection" reference in a file, but it doesn't work either.

Is there a way I can keep the original "create_connection" reference and reuse it? Or is there a workaround on it?



Solution 1:[1]

Save the original function reference only once -- not inside your function:

# Save (once)
real_create_conn = urllib3.util.connection.create_connection

def bind_ip(source_ip):
    def set_src_addr(address, timeout, *args, **kw):
        return real_create_conn(address, timeout=timeout, source_address=(source_ip, 0))

    urllib3.util.connection.create_connection = set_src_addr

while url != null and ip != null:
    bind_ip(ip)
    r = requests.get(url)

# Restore
urllib3.util.connection.create_connection = real_create_conn

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1