Python programming: is my IO object a legitimate candidate for a global variable?

I am programming a game in Python where all I / O operations are performed by an IO object (in the hope that it will be easy to swap this object for another that implements a different user interface). Almost all other objects in the game should at some point gain access to the I / O system (for example, print a message, update the position of the player, show a special effect caused by the action in the game), so my question is:

Does it make sense to reference an IO object that is accessible globally?

An alternative is to pass a reference to an I / O __init__()object in each object that should use it. I understand that this is good from a testing point of view, but is it worth the “function signature pollution”?

Thanks.

+5
source share
3 answers

Yes, this is the legal use of a global variable. If you prefer this, then as you mentioned, another option passing through a context object equivalent to this global one is another option.

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

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

, , -, , , .

+9

, .

loggerModule, print() write(), .

+1

.

. /, ( ).

, , IO - (, ).

, , . ?

, , 2 . , ? , ?

Does it really make sense to infect all the code that uses the variable, with knowledge of all the ways this can get worse?

0
source

All Articles