Strange effect with import

Terry Reedy tjreedy at udel.edu
Fri Dec 21 01:54:06 CET 2012


On 12/20/2012 5:52 PM, Jens Thoms Toerring wrote:

> You are rather likely right and I probably should have written:
> "I don't see any way to pass that variable to the object that
> is supposed to use it". Perhaps you have an idea how it could
> be done correctly when I explain the complete picture: I'm
> writing a TCP server, based on SocketServer:
>
>   server = SocketServer.TCPServer((192.168.1.10, 12345), ReqHandler)
>
> where ReqHandler is the name of a class derived from
> SocketServer.BaseRequestHandler

You misunderstood the doc. You pass the class, not the name of the class.
 From 21.19.4.1. socketserver.TCPServer Example
     server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)

MyTCPHandler is the actual class. What gets 'passed' at the C level in 
CPython is a reference that class that TCPServer can use to call it, but 
conceptually, at the Python level, think of it as the class. In the 
code, you enter the name without quotes and that expression evaluates to 
the (reference to the) class that gets passed.

If the signature required the name, the example would have had 
'MyTCPHandler', with the quotes, to pass the name as a string.

Very few builtin functions require names as strings. open('filename'), 
somebytes.encode(encoding='encoding-name', errors = 
'error-handler-name') are two that come to mind. Notice that these are 
situations where requiring a non-string object would be inconvenient at 
best.


>   class ReqHandler(SocketServer.BaseRequestHandler):
>       ...
>
> A new instance of this class is gernerated for each connection
> request to the server. In the call that creates the server I can
> only specify the name of the class but no arguments to be passed

Code those arguments directly into the handle method of your version of 
MyTCPhandler. Or if you need to override multiple methods and use the 
same values in multiple methods, override __init__ and add self.x = 
x-value statements.

-- 
Terry Jan Reedy




More information about the Python-list mailing list