I am not sure if this is ‘good python practice’, but would it be possible to, say, define a custom File-object that could do something like:
myfile = myopen('myfile.txt')
with myfile:
write('Hello World!') #notice we don't put "myfile.write(..)" here!
i.e the File-context creates a function “write()” so that we don’t have to type myfile.write(..) etc. It saves typing and makes the purpose clearer in some cases. For instance:
myboard = ChessBoard()
with ChessBoard():
make_move("e4")
make_move("e5")
give_up()
as opposed to
myboard = ChessBoard()
with ChessBoard():
make_move("e4",board=myboard)
make_move("e5",board=myboard)
give_up(board=myboard)
The question is: should I do this? and HOW can I do it? I am guessing I would have to modify the globals()-dict somehow, but that seems like a bad idea..
EDIT: Ok thanks! I got multiple good answers advising me not to do this. So I won’t do it :o)
This is not what context managers are for and, as has been remarked, I beats the “explicit is better than implicit” principle. The only way to make it work would have to work around Python’s compositional semantics, which are one of its strong points. What you can do to save typing, if there’s only a single method to be called multiple times, is:
Or with multiple such methods:
(In FP terms, this is actually partial application, not currying.)