Trying to understand f-strings...

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Trying to understand f-strings...

Post by pythoncoder » Wed Nov 10, 2021 6:41 pm

This works with string.format, with the caller being able to define the format of a value computed at run time:

Code: Select all

def bar(s="{}"):
    v = 4.2
    print(s.format(v))
Is there a way to do this with f-strings? This fails on the first line because v is undefined.

Code: Select all

def foo(s=f"{v}"):
    v = 4.2
    print(s)
It seems that the f-string is compiled, with its value, when it is declared. So this delivers 99:

Code: Select all

v = 99
def foo(s=f"{v}"):
    v = 4.2
    print(s)
So is there a way to declare an f-string which formats a value which changes at run time?
Peter Hinch
Index to my micropython libraries.

jim
Posts: 20
Joined: Tue Feb 23, 2021 10:22 pm

Re: Trying to understand f-strings...

Post by jim » Wed Nov 10, 2021 8:58 pm

Would this work for your needs?

Code: Select all

def foo(s=None):
    v = 4.2
    if s is None:
        s = f"{v}"
    print(s)

bulletmark
Posts: 59
Joined: Mon Mar 29, 2021 1:36 am
Location: Brisbane Australia

Re: Trying to understand f-strings...

Post by bulletmark » Wed Nov 10, 2021 10:45 pm

Formatted string literals (i.e. f-strings) are not intended to replace str.format() in every case. When you have a string with embedded replacement fields which you need to replace later in time, then just call .format() on it at that time. No point trying to use an f-string here.

joshfreeman
Posts: 1
Joined: Wed Nov 17, 2021 9:46 am

Re: Trying to understand f-strings...

Post by joshfreeman » Wed Nov 17, 2021 10:06 am

I am having issues to understanding this.

jim
Posts: 20
Joined: Tue Feb 23, 2021 10:22 pm

Re: Trying to understand f-strings...

Post by jim » Wed Nov 17, 2021 6:31 pm

I think it is a similar issue as trying to use an object variable as a method parameter (default argument) within the same class, which is why I proposed the above.

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Trying to understand f-strings...

Post by pythoncoder » Thu Nov 18, 2021 7:44 am

I think @bulletmark is right in this instance and string format must be used. Looking at your function:

Code: Select all

def foo(s=None):
    v = 4.2
    if s is None:
        s = f"{v}"
    print(s)
my typical call pattern would be:

Code: Select all

foo(f"{v:4.1f}")
This fails with NameError: name 'v' isn't defined.
Peter Hinch
Index to my micropython libraries.

Post Reply