views:

172

answers:

3

Hello Stackoverflow,

I'm programming a game in Python, where all IO activities are done by an IO object (in the hope that it will be easy to swap that object out for another which implements a different user interface). Nearly all the other objects in the game need to access the IO system at some point (e.g. printing a message, updating the position of the player, showing a special effect caused by an in-game action), so my question is this:

Does it make sense for a reference to the IO object to be available globally?

The alternative is passing a reference to the IO object into the __init__() of every object that needs to use it. I understand that this is good from a testing point of view, but is this worth the resulting "function signature pollution"?

Thanks.

+9  A: 

Yes, this is a legitimate use of a global variable. If you'd rather not, passing around a context object that is equivalent to this global is another option, as you mentioned.

Since I assume you're using multiple files (modules), why not do something like:

import io
io.print('hello, world')
io.clear()

This is a common way programs that have more complex I/O needs than simple printing do things like logging.

sysrqb
+1: Not truly "global", but a module global, which is far, far better. It's a Singleton.
S.Lott
+1  A: 

Yes, I think so.

Another possibility would be to create a module loggerModule that has functions like print() and write(), but this would only marginally be better.

Georg
A: 

Nope.

Variables are too specific to be passed around in the global namespace. Hide them inside static functions/classes instead that can do magic things to them at run time (or call other ones entirely).

Consider what happens if the IO can periodically change state or if it needs to block for a while (like many sockets do).

Consider what happens if the same block of code is included multiple times. Does the variable instance get duplicated as well?

Consider what happens if you want to have a version 2 of the same variable. What if you want to change its interface? Do you have to modify all the code that references it?

Does it really make sense to infect all the code that uses the variable with knowledge of all the ways it can go bad?

James