1

I have a python string which is basically a concatenation of 3 variables.I am using f-strings to make it a string. It looks like this now:

my_string = f'{getattr(RequestMethodVerbMapping, self.request_method).value} {self.serializer.Meta.model.__name__} {self.request_data['name']}'

which gives me the output:

Create IPGroup test-create-demo-098

Exactly the output that I want. However, as is obvious the line is too long and now Pylint starts complaining so I try to break up the line using multiline f-strings as follows:

my_string = f'''{getattr(RequestMethodVerbMapping, self.request_method).value} 
                {self.serializer.Meta.model.__name__} {self.request_data['name']}'''

Pylint is now happy but my string looks like this:

Create 
                  IPGroup test-create-demo-098

What is the best way of doing this so that I get my string in one line and also silence Pylint for the line being longer than 120 chars?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Amistad
  • 7,100
  • 13
  • 48
  • 75

2 Answers2

7

This is a long line by itself and, instead of trying to fit a lot into a single line, I would break it down and apply the "Extract Variable" refactoring method for readability:

request_method_name = getattr(RequestMethodVerbMapping, self.request_method).value
model_name = self.serializer.Meta.model.__name__
name = self.request_data['name']

my_string = f'{request_method_name} {model_name} {name}'

I think the following pieces of wisdom from the Zen of Python fit our problem here well:

Sparse is better than dense.

Readability counts.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
4

It is possible to concat f-strings with just whitespace in between, just like ordinary strings. Just parenthesize the whole thing.

my_string = (f'{getattr(RequestMethodVerbMapping, self.request_method).value}' 
             f' {self.serializer.Meta.model.__name__}
             f' {self.request_data["name"]}')

It will compile to exactly the same code as your one-line string.

It is even possible to interleave f-strings and non-f-strings:

>>> print(f"'foo'" '"{bar}"' f'{1 + 42}')
'foo'"{bar}"43