Reputation: 14692
def clean_word(word):
chars_to_clean = {',', ':', '.','/'} #static?
res = ''
for c in word:
if c not in chars_to_clean:
res += c
return res
In C++ I would have declared chars_to_clean
as static
so that I can minimize its scope on one hand and avoid repeated assignment on the other. How can I achieve these goals in Python?
I could make chars_to_clean
a class variable, but I'd like to reduce the scope as much as possible.
I could make it a function's attribute, but I suspect the assignment is repeated in every call.
Upvotes: 1
Views: 75
Reputation: 2251
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:
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.
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
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)
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.
Upvotes: 2
Reputation: 693
A function is an object so you can set attributes on the object and use them. They are not "private" but when reading code you can see they are closely related.
So something like that :
def clean_word(word):
res = ''
for c in word:
if c not in clean_word.chars_to_clean:
res += c
return res
clean_word.chars_to_clean = {',', ':', '.','/'}
It is not very elegant as you have to define the chars_to_clean after defining the function.
Another option where you would define the attribute while defining the function but the check hasattr is not very nice either :
def clean_word(word):
if not hasattr(clean_word, 'chars_to_clean'):
clean_word.chars_to_clean = {',', ':', '.','/'}
res = ''
for c in word:
if c not in clean_word.chars_to_clean:
res += c
return res
Upvotes: 1