简体   繁体   中英

Is an undeclared variable a reference to a function in Python?

I am trying to understand the readRequest in this Python code.

sc, sockname = s.accept()
    ...
requestType = data['RequestType']
print '[-] Type of data:',type(data)
print '[-] Data:',data
if requestType == 1:
    sc.sendall(readRequest)

readRequest looks like a variable, but if I do a search on readRequest I only find a method called readRequest, like this

def readRequest(path):

I don't see a variable called readRequest.

What is happening in this Python code? Is readRequest some kind of short hand for calling the readRequest method? If so, what parameter is getting passed?

I am looking through code I found. Is it possible that the code just has a bug or is incomplete?

Either you've found a bug, or you're wrong about what readRequest is.

It's perfectly valid to pass a function as an argument to another function (see, eg, the map function, which expects a function for its first argument).

But sc variable is almost certainly a socket , given that it comes from sc, sockname = s.accept , which means that sc.sendall is a function that takes a string of bytes and sends those bytes to the client on the other end of the socket. A function is not a string of bytes, so you will get an error that looks something like this:

TypeError: 'function' does not support the buffer interface

If that happens, most likely whoever wrote this code intended to call readRequest and pass its result, not just pass the function itself, in which case you'd fix it with:

sc.sendall(readRequest())

If, on the other hand, there's no error, that means readRequest isn't a function after all, but a string, and you just failed to find it in a search.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM