0

I am just looking to understand why I get the following results

From the following code

def sendHTTP(httpStatus):   
    status_code = 400
    reason = "Unauthorized"
    httpStatus(Code=req.status_code,Desc=req.reason)
    return httpStatus

if __name__ == '__main__':
    httpStatus = namedtuple('httpStatus','Code Desc')
    http_results = sendHTTP(httpStatus)
    print "1:",http_results

Print result is:

1: <class '__main__.httpStatus'>

while

def sendHTTP(httpStatus):

    status_code = 400
    reason = "Unauthorized"
    b = httpStatus(Code=req.status_code,Desc=req.reason)
    return b

if __name__ == '__main__':
    httpStatus = namedtuple('httpStatus','Code Desc')
    http_results = sendHTTP(httpStatus)
    print "1:",http_results

Print result is:

1: httpStatus(Code=401, Desc='Unauthorized')

Could someone explain why adding the b variable gives the values instead of the variable name?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
alexis
  • 1,022
  • 3
  • 16
  • 44

2 Answers2

2

In the first function you are ignoring the instance created, then return the namedtuple class. You could just have printed the class directly without using a function for the same result:

>>> from collections import namedtuple
>>> httpStatus = namedtuple('httpStatus','Code Desc')
>>> print httpStatus
<class '__main__.httpStatus'>

In the second function, you are assigning the instance you create to a variable, then return whatever the variable references (i.e. the instance you created).

You could forgo the variable and just return the instance directly:

return httpStatus(Code=req.status_code, Desc=req.reason)

Note that this has nothing to do with named tuples. This would happen for any class; you are returning the class object itself.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

Because in the first case, you aren't doing anything with the resulting instance from the call of the httpStatus, and then simply returning the namedtuple class which was passed as an argument.

Whereas in the second, b is assigned the instance of httpStatus which is created with

b = httpStatus(Code=req.status_code,Desc=req.reason)

which is then returned.

If you wanted the same (correct) behavior in both cases, you would want to directly

return httpStatus(Code=req.status_code,Desc=req.reason)

in your first case, instead of having the useless call without a return statement or assignment.

miradulo
  • 28,857
  • 6
  • 80
  • 93
  • Got it. I assume the following code created the instance: `httpStatus = namedtuple('httpStatus','Code Desc')` – alexis Jan 23 '17 at 08:47