Wemake-python-styleguide: Lint `f` strings better!

Created on 6 Mar 2020  路  8Comments  路  Source: wemake-services/wemake-python-styleguide

Rule request

Thesis

Currently we just do not allow people to use f strings.
But, what if our user just ignores this violation? Now it is possible to do very bad things inside f strings and we do not cover it at all.

I suggest to add TooComplexFormattedStringViolation that will be throw in case of:

  1. f'{one_name}' should raise: because we only a single name inside f string
  2. Too complex expression inside f string: like calling a lot of function, making conditions, etc
  3. Too many expressions used in f string
  4. f strings that dont have any values inside like: f'abc'
  5. Things like assert f'a {value}' should raise proper violations (WPS444 in this case), but assert f'{value}' should not

This is just a discussion at the moment.

help wanted starter pr-available rule request

Most helpful comment

From my experience, one can easily read code like this

f'smth {value}'
f'smth {dict_value["key"]}'
f'smth {list_value[0]}'
f'smth {user.get_full_name()}'
def get_full_name(self):
    return f'{self.first_name} {self.second_name} {self.last_name}'.strip()

Anything more complex is hard to read like

f'{reverse('url-name')}?{"&".join("user="+uid for uid in user_ids)}'

So:

  • value of a variable itself
  • value of a dict key by key lookup
  • value of a list item by index lookup
  • return value of a function or a method without arguments

All 8 comments

@sobolevn Can I take this issue?

Yes, but I am not sure it is ready to be implemented yet. 馃檪
Because I don't know complexity metrics to implement.

@AlwxSin do you want to share your thoughts on this one?

From my experience, one can easily read code like this

f'smth {value}'
f'smth {dict_value["key"]}'
f'smth {list_value[0]}'
f'smth {user.get_full_name()}'
def get_full_name(self):
    return f'{self.first_name} {self.second_name} {self.last_name}'.strip()

Anything more complex is hard to read like

f'{reverse('url-name')}?{"&".join("user="+uid for uid in user_ids)}'

So:

  • value of a variable itself
  • value of a dict key by key lookup
  • value of a list item by index lookup
  • return value of a function or a method without arguments

Hi again @sobolevn, we would like to take this one on.

Thanks a lot!

@sobolevn @AlwxSin we were thinking about whitelisting the cases mentioned in this thread. Are there any new cases you've thought of that should be allowed?

@ruwaid4 no more than I said before 馃し

@sobolevn Just to clarify, FormattedStringViolation should NOT be removed but TooComplexFormattedStringViolation should be added in case a user decides to ignore the former violation?

Was this page helpful?
0 / 5 - 0 ratings