You don't have to
The code is fine as you posted it (the scope is minimal and creation of such a small set does not take enough time to bother about it.
However, if you like to change the code, here is one suggestion:
Make it a default parameter
If you like to avoid repeated creation of the chars_to_clean
set, you could do the following (see "Least Astonishment" and the Mutable Default Argument):
def clean_word(word, chars_to_clean = {',', ':', '.','/'})
res = ''
for c in word:
if c not in chars_to_clean:
res += c
return res
This way the set is crated only once (when python reads the function definition) and you can reuse the function to clean different characters. This is dangerous, if you mutate the set (accidentally), which you do not do here anyway.
Make it upper case
If you want to make it clear (by convention) that this variable is a constant, change the variable name to all uppercase and don't bother about the scope
Make it a string
You can do "a" in "abcde"
in python. By changing it from a set to aa string, you can make it immutable. (Reassignment is however still possible)
Make it a class property without setter
If you want to avoid accidental reassignment/ modification, make it a class property without setter. This solution is, however, probably an overkill.
class A:
@property
def chars_to_clean(self):
return ",:./"
In this case, you can still do A.chars_to_clean = "abc"
, but A().chars_to_clean="asd"
and A().chars_to_clean[0]=w
will raise an error, the first due to the missing setter, the second due to immutability of strings.