How to avoid the redefinition of a function (PEP8 error F811)

I have the following code inside a Python function:

strings = ('TIRS10', 'TIRS11') if any(string in fields for string in strings): def transform(row): ''' Transform an input row in to a named tuple, then feed it in to a dictionary. ''' # split row in elements elements = row.split('|') # key: 1st column, replace key = replace_dot_comma_space(elements[0]) # namedtuple ect = namedtuple(key, [fields[0], fields[1]]) # feed namedtuples ect.TIRS10 = is_number(elements[1]) ect.TIRS11 = is_number(elements[2]) # feed dictionary dictionary[key] = dictionary.get(key, ect) strings = ('b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7') if any(string in fields for string in strings): def transform(row): ''' Transform an input row in to a named tuple, then feed it in to a dictionary. ''' # split row in elements elements = row.split('|') # key: 1st column, replace key = replace_dot_comma_space(elements[0]) # *** small modification for the CWV field *** fields[0] = 'cwv' # named tuples cwv = namedtuple(key, [replace_dot_comma_space(fields[0]), replace_dot_comma_space(fields[1]), replace_dot_comma_space(fields[2]), replace_dot_comma_space(fields[3]), replace_dot_comma_space(fields[4]), replace_dot_comma_space(fields[5]), replace_dot_comma_space(fields[6]), replace_dot_comma_space(fields[7]), replace_dot_comma_space(fields[8]), replace_dot_comma_space(fields[9])]) # feed named tuples cwv.subrange = to_tuple(elements[1]) cwv.b0 = is_number(elements[2]) cwv.b1 = is_number(elements[3]) cwv.b2 = is_number(elements[4]) cwv.b3 = is_number(elements[5]) cwv.b4 = is_number(elements[6]) cwv.b5 = is_number(elements[7]) cwv.b6 = is_number(elements[8]) cwv.b7 = is_number(elements[9]) cwv.rmse = is_number(elements[10]) dictionary[key] = dictionary.get(key, cwv) # feed dictionary map(transform, rows) return dictionary

and I get, for it, a redefinition of unused 'transform' from line xxx [F811]. How can I tackle this "error" so as to not use two different functions, but only one, later on inside the same function? What is the correct way to approach such a case?

Answer1:

One way is to just name them as transform1 and transform2 and put map inside if-else:

if condition1: transform = transform1 else: # if condition2 transform = transform2 map(transform, row)

Also, it is not good to reuse variables like strings: it could introduce subtle errors. It is also not good to change dictionary variable implicitely. It is always better to pass such things explicitely and return changed objects also explicitely.

If there are more transforms like the above, it's cleaner to refactor is object-oriented style where .transform() is a method of tirs-class or b-class. Then dictionary will be naturally an attribute, part of the Transformer class state, and not global.

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:How to avoid the redefinition of a function (PEP8 error F811)