-
Notifications
You must be signed in to change notification settings - Fork 97
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
f-strings for Berry #346
Comments
Also see discussion on Tasmota Discord. |
Done: #355 |
Hi @s-hadinger I'm looking if there is a way to use format string like in python: # this is Python, not Berry
# fulltopic = "{prefix}/{topic}/{subtopic}"
fulltopic=string.replace(string.replace(tasmota.cmd("fulltopic")['FullTopic'],"%prefix%","{prefix}"),"%topic%","{topic}")+"{subtopic}"
# publish_topic = "cmnd/devname/power"
publish_topic = fulltopic.format(prefix="cmnd", topic="devname", subtopic="power")
# or
publish_topic = fulltopic.format(**{"prefix":"cmnd", "topic":"devname", "subtopic":"power"}) As you imagine the idea is to use named variable in the format string instead of positional values Thanks |
f-strings are purely compile time synctactic sugar to the |
Yes, indeed I simply string replace:
|
If you really want, you can have non-constant f-strings expanded by going via
|
I wouldn't recommend using compile with dynamic content. This is always dangerous ; like eval() in many languages |
Now that I have some decent experience with programming in Berry, I'm am not completely happy with string formatting.
string.format()
is slightly verbose. I would like to add an equivalent to Python's f-strings.Example:
string.format("id=%i cluster=0x%04X name=%s", id, cluster, self.name)
would become:
f"id={id:i} cluster={cluster:04X} name={self.name}"
I made a POC that sounds promising. Changing the parser would be a daunting task. Instead, I use a "transpiler" approach. The lexer contains code to detect f-string syntax and rewrite the code to generate the string.format syntax.
The lexer transforms
f"id={id:i} cluster={cluster:04X} name={self.name}"
to("id=%i cluster=0x%04X name=%s", id, cluster, self.name)
and then just feeds the normal parser.The text was updated successfully, but these errors were encountered: