Help a C++ escapee!

Paul Melis paul at science.uva.nl
Thu Jun 7 05:31:10 EDT 2007


Hello,

Simon Pickles wrote:
> Can someone help me leave the murky c++ world and enter shiny pythonland?

Welcome!

> I have a problem with importing and global variables, here's my code:
> 
> [...]
 >
> When run, I come unstuck here:
> 
>            self.clientSocket, self.clientAddress = network.accept()
> 
> I get a nameError on 'network', yet it is one in the global namespace, 
> defined in server.py before CServerThread.Listen() is called.

That won't work (as you found out :)). You need to make 'network' 
available within socketManager.py. Each module on its own has a 
namespace, there isn't such a thing as a global namespace that is 
accessible from all modules, like you are used to in C or C++.

So when you access the variable 'network' in module socketManager it is 
looked up in that module's namespace. When you read through 
socketManager.py (without looking at any other code) you will see that 
'network' isn't being defined anywhere. I would solve it like this:

Pass it as a parameter to CNetworkManager's and CServerThread's 
constructor and store it as an instance variable, i.e. for CNetworkManager:

class CNetworkManager:
    def __init__(self, network):
        self.network = network
        ...

and then later pass it again to the thread you're creating.

Another way to have something a bit more like a global namespace would 
be to create a new module, say we name it globals.py.

-------------------------
# globals.py

# initially, no network set
network = None
-------------------------

Each module that needs access to globals would then import the globals 
module and access its variables. So, server.py would do

import globals
globals.network = CNetworkManager()
globals.network.Listen()

and socketManager.py would do

import globals

      ...
      self.clientSocket, self.clientAddress = globals.network.accept()

(You could also selectively import the network variable of course with 
"from globals import network").

Hope this helps,
Paul





More information about the Python-list mailing list