Python f-strings


#1

I must admit that I’ve really fallen in love with the new f-string feature in Python 3.6. Although they’re nice for producing output like this:

>>> name = 'Guido'
>>> n = 37
>>> print(f'{name} has {n} messages')
Guido has 37 messages
>>>>

I think my favorite use is for other stuff like __repr__() methods, exceptions and other stuff. For example:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return f'Point({self.x}, {self.y})'

Or maybe in some error checking code:

if not instance(value, SomeType):
    raise TypeError(f'Expected SomeType. Got {type(value)}')

Sure, I could use more traditional string formatting for both of these, but the f-strings are so much more compact and readable in my opinion.

If there’s any one feature that might make me move my projects to Python 3.6 and newer, it’s probably this. After you start using f-strings, you just don’t want to go back. Sorry Python 3.5.


#2

fstrings a very handy, but for me the most useful thing is async generators and async comprehension. They are the reason I said goodbye to python 3.5. The lack of them in python 3.5 maded me use and modify this . And with them can do things this way. Significant improvement.
By the way, I’ve learned def f(arg, *args): trick from operator.itemgetter and used it in def concat(aiter, *aiters) which behaves differently when more than one async iterator have been passed to it. In the first case it means that we have an iterator, that would return iterables that we need to concat, and in the second case it means that we have iterators that we need to concat with each other. Why itertools.chain isn’t using the same trick and defines chain.from_iterable instead?


#3

Hello David,

In the last example, there needs to be parenthesis for SomeType?


#4

I think it’s okay. SomeType was meant to be a literal (like float, int, etc.)