Reputation: 980
I searched around but I did not found the answer to this question.
Is there any aesthetic, pythonic way to create temporary variables in an arbitrary scope so I am sure they won't ever appear outside this scope ?
For exemple in OCaml, I can write :
let x = 3 and y = 5 in z = x + y
I'd love to do some stuff like this in Python. For exemple, let's imagine I create a module talker.py
with a lot of useful functions, and each of them uses a variable that I don't want to copy again and again.
# talker.py
sentance = ( 'Has provinciae has dictione emergunt sorte aptae'
'iuris navigerum nusquam iuris in natura sorte aptae visitur'
'in verum dictione flumen.' )
def talk() :
print sentance
def talk_loudly() :
print sentance.upper()
def any_other_useful_function :
# do stuff using sentance
Then I want to use all of these wonderful functions in another file, but :
sentance
: this variable has done it's job, now I want it to fall in darkness and to be forgotten.But if I call this module with import talk
or from talk import *
, this second condition won't be respected.
This is an example of where I could use a "special scope for temporary variables", even if it is not the only situation in which I wish I had this at range.
I thought about using the with ... :
statement but I wasn't satisfied with the result.
Any idea is welcomed, but I am looking for the most aesthetic and least wordy manner to proceed.
Upvotes: 0
Views: 965
Reputation: 36033
Firstly, sentance
isn't temporary. Those functions are relying on its existence. You could del sentance
and it would be gone but the functions would throw an error.
A common Python convention is to prefix the name with an underscore. This signals that the variable is 'protected'. It doesn't do anything, but programmers know that they probably shouldn't access it from outside the module (or class).
Upvotes: 1
Reputation: 362796
You can define the __all__
name on your module, to control the names which will be available when you are using from talk import *
.
Upvotes: 2