As Classes are first-class objects in Python, we can pass them to functions. For example, here is some code I’ve come across:
ChatRouter = sockjs.tornado.SockJSRouter(ChatConnection, '/chat')
where ChatConnection is a Class defined in the same module. I wonder what would be the common user case(s) for such practice?
In addition, in the code example above, why is the variable ‘ChatRouter’ capitalized?
Without knowing anything else about that code, I’d guess this:OK, I looked at the source. Below the line is incorrect, although plausible. Basically what the code does is use
ChatConnectionto create aSessionobject which does some other stuff.ChatRouteris just a badly named regular variable, not a class name.SockJSRouteris a class that takes another class (call itconnection) and a string as parameters. It uses__new__to create not an instance ofSockJSRouter, but an instance of a special class that uses (possibly subclasses)connection. That would explain whyChatRouteris capitalized, as it would be a class name. The returned class would useconnectionto generalize a lot of things, asconnectionwould be responsible for handling communicating over a network or whatever. So by using differentconnections, one could handle different protocols.ChatConnectionis probably some layer over IRC.So basically, the common use case (and likely the use here) is generalization, and the reason for the BactrianCase name is because it’s a class (just one generated at runtime).