A global or module-level variable?

B

Bret

This has to be easier than I'm making it....

I've got a module, remote.py, which contains a number of classes, all
of whom open a port for communication. I'd like to have a way to
coordinate these port numbers akin to this:

So I have this in the __init__.py file for a package called cstore:

nextport=42000

def getNextPort():
nextport += 1
return nextport

:
Then, in the class where I wish to use this (in cstore.remote.py):
:


class Spam():

def __init__(self, **kwargs):
self._port = cstore.getNextPort()

I can't seem to make this work, though. As given here, I get an
"UnboundLocalError:local variable 'nextport' referenced before
assignment". When I try prefixing the names inside __init__.py with
"cstore.", I get an error that the global name "cstore" is not
defined.

I've been looking at this long enough that my eyes are blurring. Any
ideas?

BTW, the driving force here is that I'm going to need to wrap this in
some thread synchronization. For now, though, I'm just trying to get
the basics working.

Thanks!


Bret
 
P

Paul Rubin

Bret said:
nextport=42000

def getNextPort():
nextport += 1
return nextport

If you have to do it that way, use:

def getNextPort():
global nextport
nextport += 1
return nextport

the global declaration stops the compiler from treating nextport as
local and then trapping the increment as to an uninitialized variable.
 
B

Bret

It's simple, clear and works fine, why make it more complicated?
Unless you have additional requirements, like a multithreaded program.

Ultimately, it will be multithreaded -- and I had intended to wrap the
access to the global member in a lock to ensure only one thread could
get a value at any point. It might also become multiprocess (ugh!)
and so might need to live in its own SocketServer some day. But for
now, I agree. Simple is good. I just wanted to be sure I wasn't
oversimplifying, you know?

Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,828
Latest member
LauraCastr

Latest Threads

Top