skyork
skyork

Reputation: 7391

Why do we want to pass a Class to a function

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?

Upvotes: 0

Views: 220

Answers (2)

Peter C
Peter C

Reputation: 6307

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 ChatConnection to create a Session object which does some other stuff. ChatRouter is just a badly named regular variable, not a class name.


SockJSRouter is a class that takes another class (call it connection) and a string as parameters. It uses __new__ to create not an instance of SockJSRouter, but an instance of a special class that uses (possibly subclasses) connection. That would explain why ChatRouter is capitalized, as it would be a class name. The returned class would use connection to generalize a lot of things, as connection would be responsible for handling communicating over a network or whatever. So by using different connections, one could handle different protocols. ChatConnection is 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).

Upvotes: 1

Eli Bendersky
Eli Bendersky

Reputation: 273526

Passing classes around may be useful for customization and flexible code. The function may want to create several objects of the given class, so passing it a class is one way to implement this (another would be to pass some kind of factory function). For example, in the example you gave, SockJSRouter ends up passing the connection class to Session, which then uses it to construct a new connection object.

As for ChatRouter, I suppose this is just a naming convention. While Python programmers are advised to follow PEP 8, and many do, it's not strictly required and some projects settle on different naming conventions.

Upvotes: 1

Related Questions