Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?
On 28Jan2023 18:55, Jach Feng wrote: Mark Bourne 在 2023年1月28日 星期六晚上10:00:01 [UTC+8] 的信中寫道: I notice you explain the need to enclose the equation in quotes if it contains spaces. That's not even a feature of your application, but of the shell used to call it. So why so much objection to explaining the need for "--"? Depending on the shell, there are other cases where quoting might be needed, e.g. if the equation includes a "*" or "?" and happens to look like a pattern matching files in the current directory (most shells I've used pass the pattern unchanged if it doesn't match any files). In bash, if a "$" is used I'd need to enclose that in 'single quotes' (can't even use "double quotes" for that one). You can't really expect to document all that sort of thing, because it depends on which shell the user happens to run your application from - you just have to trust the user to know or learn how to use their shell. Thank you for detail explanation of the role the shell is involved in this problem. I'm very appreciated! The shell has basicly _nothing_ to do with your problems. By the time you've got sys.argv in your Python programme you will have no idea whether quotes were used with an argument. (UNIX/POSIX, not Windows, where things are ... more complex.) This means you don't know if the use typed: -4.5 or "-4.5" You'll just get a string '4.5' in your Python programme both ways. All the quotes in the shell do is delimit what things should be kept together as a single argument versus several, or where variables should be interpolated when computing arguments etc. It's just _shell_ punctuation and the invoked programme doesn't see it. It seems that a CLI app may become very complex when dealing with different kind of shell, and may not be possible to solve its problem. It doesn't matter what shell is used. The just controls what punctuation the end user may need to use to invoke your programme. You programme doesn't need to care (and can't because it doesn't get the quotes etc, only their result). So why so much objection to explaining the need for "--"? Because of using " to enclose a space separated string is a common convention, and adding a "--" is not:-) They're unrelated. As others have mentioned, "--" is _extremely_ common; almost _all_ UNIX command like programmes which handle -* style options honour the "--" convention. _argparse_ itself honours that convention, as does getopt etc. The "--" convention has nothing to do with the shell. Cheers, Cameron Simpson -- https://mail.python.org/mailman/listinfo/python-list
Re: Evaluation of variable as f-string
On 1/28/2023 2:50 PM, Johannes Bauer wrote: Am 28.01.23 um 02:51 schrieb Thomas Passin: This is literally the version I described myself, except using triple quotes. It only modifies the underlying problem, but doesn't solve it. Ok, so now we are in the territory of "Tell us what you are trying to accomplish". And part of that is why you cannot put some constraints on what your string fragments are. The example I gave, copied out of your earlier message, worked and now you are springing triple quotes on us. It works in this particular case, yes. Just like the example I gave in my original case: eval("f'" + s + "'") "works" if there are no apostrophes used. And just like eval("f\"" + s + "\"") "works" if there are no quotation marks used. I don't want to have to care about what quotation is used inside the string, as long as it could successfully evaluate using the f-string grammar. Stop with the rock management already and explain (briefly if possible) what you are up to. I have a string. I want to evaluate it as if it were an f-string. I.e., there *are* obviously restrictions that apply (namely, the syntax and semantics of f-strings), but that's it. Well, yes, we do see that. What we don't see is what you want to accomplish by doing it, and why you don't seem willing to accept some restrictions on the string fragments so that they will evaluate correctly. IOW, perhaps there is a more practical way to accomplish what you want. Except that we don't know what that is. -- https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?
On Sun, 29 Jan 2023 at 14:29, Jach Feng wrote: > Thank you for detail explanation of the role the shell is involved in this > problem. I'm very appreciated! > > It seems that a CLI app may become very complex when dealing with different > kind of shell, and may not be possible to solve its problem. But the good > thing in my app is that I need only to handle math equation:-) > > > So why so much objection to explaining the need for "--"? > Because of using " to enclose a space separated string is a common > convention, and adding a "--" is not:-) Double hyphen is incredibly common. On most Unix shells, double quotes are just one way of marking that a space should be included in an argument rather than separating (others include single quotes, escaping the space with a backslash, and changing the field separator). Of course, everything is conventions, not requirements, but it's generally better to let the person's shell define the argument splitting; that way, if your script is called from another process, it's dead easy to control the splitting yourself (just pass an array/list of arguments to the subprocess spawner). Maybe you come from Windows, where there are fewer conventions and less shell parsing, but argparse follows Unix conventions, so if you don't want Unix conventions, don't use argparse. Just read sys.argv directly. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Evaluation of variable as f-string
On Sun, 29 Jan 2023 at 14:36, Stefan Ram wrote: > > Johannes Bauer writes: > >I have a string. I want to evaluate it as if it were an f-string. I.e., > >there *are* obviously restrictions that apply (namely, the syntax and > >semantics of f-strings), but that's it. > > (This message was written for Usenet. If you read it in a > mailing list or the Web, it has been stolen from Usenet.) > I'm curious as to the copyright protections available to you, but if you're going to threaten python-list's owners with legal action for daring to rebroadcast a public post, I would have to recommend that you get promptly banned from the list in order to reduce liability. What's so bad about mailing lists that you don't want your messages to be seen on them? ChrisA -- https://mail.python.org/mailman/listinfo/python-list
RE: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?
Jack, I get uneasy when someone thinks a jackhammer is a handy dandy tool for pushing in a thumbtack that is sitting on my expensive table. I agree it is quite easy to grab some code that does lot of things and also does something truly minor, and use it for that purpose. Sometimes the cost is that it is far slower. I mean if I want to print the smaller of variables alpha and beta containing integers, I could combine them in something like a list or array and call a nifty sort() function someone wrote that takes a function argument that lets you compare whatever is needed and it likely will work. You get back the result and print the first item in the sorted output or maybe the last. You could have used a simpler function like min(alpha, beta) and skipped making a list of them. Heck, you could have used a fairly simple if statement. But if you searched the internet and found a function that takes any number of data items and performs many statistical tests on it tat start with things like mean, median and mode and continues to calculate standard deviation, and skew and standard error and also the min/max/range. Sounds good. It returns some structure/object and you dig into it and find the minimum and you are done! It sounds like the jackhammer approach to me. In your case, there is indeed nothing wrong with using the function to help parse the command line arguments and you are being told that it generally works EXCEPT when it is documented NOT TO WORK. It was designed to deal with UNIX conventions so you could call a program with a mix of optional flags and then optional arguments such as filenames or anything else or ALMOST anything else. The early design allowed something like to list files using: ls - la *.c or ls - l -a *.c Or many more variations that can include newer ways that use longer options. People ran into the problem of having some options that included a word following them that is to be parsed as part of that option and other enhancements. The minus sign or hyphen was chosen and is not trivial to change. So the idea was to add a flag with two minus signs that has no meaning other than to say that anything after that is to be somewhat ignored as not being a flag. Thus it is safe for any further arguments to start with a minus sign. How does that line up with some of the advice you got? One idea was to have your users told they should add a " -- " (without quotes) before the formula you want to evaluate. Another was asking if you had a more complex command line with many options that needed a swiss army knife approach. If not, since you have formulas starting with a minus sign that may be used, consider NOT using a tool you admit you did not understand. And since python like many languages provides you with a data structure that already holds the info you need, use the thumbtack approach or find or write a different library function that extracts what you need in an environment where it is NOT looking for things with a minus sign. You know when you go to a doctor and ask why a part of your skin is bleeding and so on, and you admit you keep scratching yourself, rather than suggesting complex surgeries or putting your hands in a cast to keep you from scratching, they may first try telling you to NOT DO THAT and let it heal. Do note a final point. There is nothing magical about using a minus sign in UNIX and they could have insisted say that command line arguments be placed in square brackets or some other method to identify them. It seemed harmless to use a minus sign at the time. But the programs they includes starting using so many allowed tweaks of many kinds, that it got really hard to parse what was being asked and thus several libraries of functions have been built that manage all that. Your problem is far from unique as any program trying to deal with an argument for a filename that begins with a minus sign will have a similar problem. Programs like grep often take an argument that is a regular expression or other utilities take a "program" that also may for whatever reason start with a minus sign. Some people ask a question and you have asked many here, and got answers. Usually you accept what people tell you better. I am trying to say that the issue is not whether you are using the wrong tool in general. It is that NOW that you know there is sometimes a problem, you resist understanding it was never designed to do what you want. -Original Message- From: Python-list On Behalf Of Jach Feng Sent: Saturday, January 28, 2023 12:04 AM To: python-list@python.org Subject: Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? Jach Feng 在 2023年1月22日 星期日上午11:11:22 [UTC+8] 的信中寫道: > Fail on command line, > > e:\Works\Python>py infix2postfix.py "-4^2+5.3*abs(-2-1)/2" > usage: infix2postfix.py [-h] [infix] > infix2postfix.py: error: unrecognized arguments: -4^2+5.3*abs(-2-1)/2 > > Also fail in REPL,
Re: Usenet vs. Mailing-list
Jon Ribbens writes: > On 2023-01-29, Ben Bacarisse wrote: >> "Peter J. Holzer" writes: >> >>> On 2023-01-27 21:04:58 +, Ben Bacarisse wrote: mutt...@dastardlyhq.com writes: > Hi It looks like you posted this question via Usenet. comp.lang.python is essentially dead as a Usenet group. It exists, and gets NNTP versions of mail sent to the mailing list, but nothing posted to the group via NNTP get send on the mailing list. >>> >>> This is wrong. I did get Muttley's any your postings via the >>> mailing-list. >> >> Ah, OK. I thought that was the case but I am obviously wrong. Has >> there been a change, or have I been wrong for a long time!? > > I'm not aware of any significant period in the last twenty-one years > that it hasn't been working. Although sometimes it does feel like it > isn't, in that I reply to a post with an answer and then several > other people reply significantly later with the same answer, as if > my one had never existed... but whenever I check into it, my message > has actually always made it to the list. I have had the same experience and, as a result, I rarely post. Maybe what I have to say is simply not interesting! -- Ben. -- https://mail.python.org/mailman/listinfo/python-list
Re: Usenet vs. Mailing-list
On 2023-01-29, Ben Bacarisse wrote: > "Peter J. Holzer" writes: > >> On 2023-01-27 21:04:58 +, Ben Bacarisse wrote: >>> mutt...@dastardlyhq.com writes: >>> >>> > Hi >>> >>> It looks like you posted this question via Usenet. comp.lang.python is >>> essentially dead as a Usenet group. It exists, and gets NNTP versions >>> of mail sent to the mailing list, but nothing posted to the group via >>> NNTP get send on the mailing list. >> >> This is wrong. I did get Muttley's any your postings via the >> mailing-list. > > Ah, OK. I thought that was the case but I am obviously wrong. Has > there been a change, or have I been wrong for a long time!? I'm not aware of any significant period in the last twenty-one years that it hasn't been working. Although sometimes it does feel like it isn't, in that I reply to a post with an answer and then several other people reply significantly later with the same answer, as if my one had never existed... but whenever I check into it, my message has actually always made it to the list. -- https://mail.python.org/mailman/listinfo/python-list
Re: Usenet vs. Mailing-list
"Peter J. Holzer" writes: > On 2023-01-27 21:04:58 +, Ben Bacarisse wrote: >> mutt...@dastardlyhq.com writes: >> >> > Hi >> >> It looks like you posted this question via Usenet. comp.lang.python is >> essentially dead as a Usenet group. It exists, and gets NNTP versions >> of mail sent to the mailing list, but nothing posted to the group via >> NNTP get send on the mailing list. > > This is wrong. I did get Muttley's any your postings via the > mailing-list. Ah, OK. I thought that was the case but I am obviously wrong. Has there been a change, or have I been wrong for a long time!? There may be a timing issue because I tried to find a reply a Usenet injected post from a mailing-list user and, at the time I looked, I could not find one. -- Ben. -- https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?
Mark Bourne 在 2023年1月28日 星期六晚上10:00:01 [UTC+8] 的信中寫道: > Jach Feng wrote: > > Jach Feng 在 2023年1月22日 星期日上午11:11:22 [UTC+8] 的信中寫道: > >> Fail on command line, > >> > >> e:\Works\Python>py infix2postfix.py "-4^2+5.3*abs(-2-1)/2" > >> usage: infix2postfix.py [-h] [infix] > >> infix2postfix.py: error: unrecognized arguments: -4^2+5.3*abs(-2-1)/2 > >> > >> Also fail in REPL, > >> > >> e:\Works\Python>py > >> Python 3.8.8 (tags/v3.8.8:024d805, Feb 19 2021, 13:08:11) [MSC v.1928 32 > >> bit (Intel)] on win32 > >> Type "help", "copyright", "credits" or "license" for more information. > > import argparse > > parser = argparse.ArgumentParser(description='Convert infix notation to > > postfix') > > parser.parse_args("-4^2+5.3*abs(-2-1)/2") > >> usage: [-h] > >> : error: unrecognized arguments: - 4 ^ 2 + 5 . 3 * a b s ( - 2 - 1 ) / 2 > >> > >> Just can't figure out where is wrong!? > >> > >> --Jach > > I have to admit that I don't know the background upon which the argparse > > was built. The good side is that I don't carry its historical knowledge ( > > or burden?), that's why I can use it in a new way which may make someone > > feel uneasy. > If you can use it in the way you want, that's great. I thought you were > asking here because you *couldn't* use it the way you want. > > You're writing a command-line application. Your users are either > already familiar with the conventions of command-line applications, or > they'll soon need to be. > > If your application supports options beginning with a "-" (which is what > argparse gives you, even if only the default "-h" and "--help" options > are actually valid), and you also need to be able to pass positional > arguments which begin with a "-", you need some way for the user to > indicate whether any particular argument is an option or positional. > Using "--" to indicate that all subsequent arguments are positional, not > options, is a common convention. > > Some of your users might already be familiar with that convention from > other command-line tools. By using the same convention, you'd be making > it easier for them to use yours. Others might not already be familiar > with the convention, but by being consistent with other tools you'd > still be helping them when they eventually do come across it elsewhere. > You can always include an explanation of using "--" in your usage output > or other documentation. > > Apart from dealing with how to pass an argument beginning with "-", your > users will also likely have to deal with the features of whichever shell > they're using, which you have no control over. For example, it's quite > common to need to enclose an argument in quotes if it contains spaces. > It may also be necessary to use quotes if certain special characters are > used, such as "*", "?" or "$" (perhaps "%" on Windows). > > The reason I am still keep on using argparse on this "one positional > > argument only" CLI app is that I can't see what advantage I can get when > > writing code to handling sys.argv directly for the following two > > situations, > > - > > e:\Works\Python>py infix2postfix.py > > usage: infix2postfix.py [-h] infix > > infix2postfix.py: error: the following arguments are required: infix > > > > e:\Works\Python>py infix2postfix.py -h > > usage: infix2postfix.py [-h] infix > > > > Convert infix notation to postfix > > > > positional arguments: > > infix Put equations in quote if there is space in it and separate each one > > with a comma, ie. > > "-4^2+5.3*abs(-2-1)/2, abs(Abc)*(B+C)/D, (-3) * sqrt(1-(x1/7)*(y1/7)) * > > sqrt(abs((x0-4.5)/(y0-4)))" > > > > optional arguments: > > -h, --help show this help message and exit > > - > > > > comparing with code using the argparse below, > > > > import argparse > > sample = "-4^2+5.3*abs(-2-1)/2, abs(Abc)*(B+C)/D, (-3) * > > sqrt(1-(x1/7)*(y1/7)) * sqrt(abs((x0-4.5)/(y0-4)))" > > parser = argparse.ArgumentParser(description='Convert infix notation to > > postfix') > > parser.add_argument('infix', > > help='Put equations in quote if there is space in it and separate each one > > with a comma, ie. "{}"'.format(sample)) > > > > import sys > > if len(sys.argv) > 1 and not '-h' in sys.argv: > > sys.argv.insert(1, '--') > > args = parser.parse_args() > Personally, I do quite often use argparse even for simple cases, partly > because it produces nice usage details, and deals with wrapping the > output to whatever width the console is. But I work with it rather than > against it, and accept that a "--" is needed if a positional argument > starts with a "-". > > I notice you explain the need to enclose the equation in quotes if it > contains spaces. That's not even a feature of your application, but of > the shell used to call it. So why so much objection to explaining the > need for "--"? > > Depending on the shell, there are other cases where quoting might be > needed,
Re: Usenet vs. Mailing-list
On Sun, 29 Jan 2023 at 12:07, Chris Green wrote: > > Chris Green wrote: > > Jon Ribbens wrote: > > > On 2023-01-28, Peter J. Holzer wrote: > > > > On 2023-01-27 21:04:58 +, Ben Bacarisse wrote: > > > >> It looks like you posted this question via Usenet. comp.lang.python is > > > >> essentially dead as a Usenet group. It exists, and gets NNTP versions > > > >> of mail sent to the mailing list, but nothing posted to the group via > > > >> NNTP get send on the mailing list. > > > > > > > > This is wrong. I did get Muttley's any your postings via the > > > > mailing-list. > > > > > > Yes, it's certainly false. I only ever post via the newsgroup, > > > and I can see my postings reach the list because they appear > > > in the list archive on the web. > > > > > As far as I am aware the mirroring of the Python mailing list on > > comp.lan.python works perfectly. I love gmane! :-) > > > That is, of course, comp.lang.python. Too much wine! :-) > You can run Python with wine, but it runs natively and that's usually better :) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Evaluation of variable as f-string
On Sun, 29 Jan 2023 at 11:56, Johannes Bauer wrote: > > Am 28.01.23 um 00:41 schrieb Chris Angelico: > > On Sat, 28 Jan 2023 at 10:08, Rob Cliffe via Python-list > > wrote: > >> > >> Whoa! Whoa! Whoa! > >> I appreciate the points you are making, Chris, but I am a bit taken > >> aback by such forceful language. > > > > The exact same points have already been made, but not listened to. > > Sometimes, forceful language is required in order to get people to > > listen. > > An arrogant bully's rationale. Personally, I'm fine with it. I've been > to Usenet for a long time, in which this way of "educating" people was > considered normal. But I do think it creates a deterring, toxic > environment and reflects back to you as a person negatively. Arrogant bully? Or someone who has tried *multiple times* to explain to you that what you're asking for is IMPOSSIBLE, and you need to ask a better question if you want a better answer? If that's "bullying", then fine, ban me for bullying, and go find somewhere else where you'll be coddled and told that your question is fine, it's awesome, and yes, wouldn't it be nice if magic were a thing. > Exactly. This is precisely what I want to avoid. Essentially, proper > quotation of such a string requires to write a fully fledged f-string > parser, in which case the whole problem solves itself. > > >>> Don't ask how to use X to do Y. Ask how to do Y. > >> Good advice. > > > > Exactly. As I have shown, asking how to use f-strings to achieve this > > is simply not suitable, and there's no useful way to discuss other > > than to argue semantics. If we had a GOAL to discuss, we could find > > much better options. > > I was not asking how to use f-strings. I was asking to evaluate a string > *as if it were* an f-string. Those are two completely different things > which you entirely ignored. They're not different things, because what you asked for is NOT POSSIBLE without the caveats that I gave. It is *fundamentally not possible* to "evaluate a string as if it were an f-string", other than by wrapping it in an f-string and evaluating it - with the consequences of that. > In other words, if there were a magic function: > > evalfstring(s, x = x) > > That would have been the ideal answer. There does not seem to be one, > however. So I'm back to silly workarounds. > Right. Exactly. Now if you'd asked for what you REALLY need, maybe there'd be a solution involving format_map, but no, you're so utterly intransigent that you cannot adjust your question to fit reality. If that makes me a bad guy, then fine. I'll be the bad guy. But you're not going to change the laws of physics. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: bool and int
On Sun, 29 Jan 2023 at 11:27, rbowman wrote: > > On Fri, 27 Jan 2023 21:35:11 -0800 (PST), Grant Edwards wrote: > > > In Unix shells, a return code of 0 is true and non-0 is false. > > That carries over to some C functions like strcmp() although it's more > complex. strcmp() returns the value of subtracting the nth character of > string b from string a if the value is not 0. For matching strings, the > result is 0 for all character positions. > > This plays nicely with sorting functions but naive programmers assume it's > a boolean and strcmp("foo", "foo") should return 1 or true when the > strings match. > > Returning 0 for success gives you much more latitude in return values. That's not really about booleans, it's more like "imagine subtracting one string from another". You can compare two integers by subtracting one from another; you'll get a number that's less than zero, zero, or greater than zero, just like with strcmp. And yes, that plays perfectly with sorting functions. So when you want to compare strings, what do you do? You make something that subtracts one string from another. It's "String Compare", not "Are Strings Equal", so it doesn't return a boolean. Zero for equal makes very good sense, even though a "strings equal" function would return zero for non-equal. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Usenet vs. Mailing-list
On Sat, 28 Jan 2023 20:07:44 +, Chris Green declaimed the following: >As far as I am aware the mirroring of the Python mailing list on >comp.lan.python works perfectly. I love gmane! :-) Is gmane's gmane.comp.python.general allowing posts to go through again? I had to revert to comp.lang.python some time back when gmane kept rejecting outgoing posts. -- Wulfraed Dennis Lee Bieber AF6VN wlfr...@ix.netcom.comhttp://wlfraed.microdiversity.freeddns.org/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Usenet vs. Mailing-list
Chris Green wrote: > Jon Ribbens wrote: > > On 2023-01-28, Peter J. Holzer wrote: > > > On 2023-01-27 21:04:58 +, Ben Bacarisse wrote: > > >> It looks like you posted this question via Usenet. comp.lang.python is > > >> essentially dead as a Usenet group. It exists, and gets NNTP versions > > >> of mail sent to the mailing list, but nothing posted to the group via > > >> NNTP get send on the mailing list. > > > > > > This is wrong. I did get Muttley's any your postings via the > > > mailing-list. > > > > Yes, it's certainly false. I only ever post via the newsgroup, > > and I can see my postings reach the list because they appear > > in the list archive on the web. > > > As far as I am aware the mirroring of the Python mailing list on > comp.lan.python works perfectly. I love gmane! :-) > That is, of course, comp.lang.python. Too much wine! :-) -- Chris Green · -- https://mail.python.org/mailman/listinfo/python-list
Re: Evaluation of variable as f-string
On Sun, 29 Jan 2023 at 11:53, Johannes Bauer wrote: > I don't want to have to care about what quotation is used inside the > string, as long as it could successfully evaluate using the f-string > grammar. > Not possible. An f-string can contain other f-strings, and it is entirely possible to use EVERY quote type. So you can never add quotes around the outside of a string and then evaluate it as an f-string, without making sure that it doesn't already contain that string. (That MAY be changing in a future version of Python, but it's currently true.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Usenet vs. Mailing-list
Jon Ribbens wrote: > On 2023-01-28, Peter J. Holzer wrote: > > On 2023-01-27 21:04:58 +, Ben Bacarisse wrote: > >> It looks like you posted this question via Usenet. comp.lang.python is > >> essentially dead as a Usenet group. It exists, and gets NNTP versions > >> of mail sent to the mailing list, but nothing posted to the group via > >> NNTP get send on the mailing list. > > > > This is wrong. I did get Muttley's any your postings via the > > mailing-list. > > Yes, it's certainly false. I only ever post via the newsgroup, > and I can see my postings reach the list because they appear > in the list archive on the web. > As far as I am aware the mirroring of the Python mailing list on comp.lan.python works perfectly. I love gmane! :-) -- Chris Green · -- https://mail.python.org/mailman/listinfo/python-list
Re: Evaluation of variable as f-string
Am 27.01.23 um 23:10 schrieb Christian Gollwitzer: Am 27.01.23 um 21:43 schrieb Johannes Bauer: I don't understand why you fully ignore literally the FIRST example I gave in my original post and angrily claim that you solution works when it does not: x = { "y": "z" } s = "-> {x['y']}" print(s.format(x = x)) Traceback (most recent call last): File "", line 1, in KeyError: "'y'" This. Does. Not. Work. It's because "you're holding it wrong!". Notice the error message; it says that the key 'y' does not exist. Ah, that is neat! I didn't know that. Thanks for the info. In my case, I do also however want to have some functionality that actually does math or even calls functions. That would be possible with templates or f-strings, but not format: x = { "t": 12345 } s = "{x['t'] // 60:02d}:{x['t'] % 60:02d}" print(s.format(x = x)) Traceback (most recent call last): File "", line 1, in KeyError: "'t'" and s = "{x[t] // 60:02d}:{x[t] % 60:02d}" print(s.format(x = x)) Traceback (most recent call last): File "", line 1, in ValueError: Only '.' or '[' may follow ']' in format field specifier but of course: print(f"{x['t'] // 60:02d}:{x['t'] % 60:02d}") 205:45 Best, Johannes -- https://mail.python.org/mailman/listinfo/python-list
Re: Evaluation of variable as f-string
Am 28.01.23 um 00:41 schrieb Chris Angelico: On Sat, 28 Jan 2023 at 10:08, Rob Cliffe via Python-list wrote: Whoa! Whoa! Whoa! I appreciate the points you are making, Chris, but I am a bit taken aback by such forceful language. The exact same points have already been made, but not listened to. Sometimes, forceful language is required in order to get people to listen. An arrogant bully's rationale. Personally, I'm fine with it. I've been to Usenet for a long time, in which this way of "educating" people was considered normal. But I do think it creates a deterring, toxic environment and reflects back to you as a person negatively. Addressing your points specifically: 1) I believe the quote character limitation could be overcome. It would need a fair amount of work, for which I haven't (yet) the time or inclination. No problem. Here, solve it for this string: eval_me = ' f"""{f\'\'\'{f"{f\'{1+2}\'}"}\'\'\'}""" ' F-strings can be nested, remember. Exactly. This is precisely what I want to avoid. Essentially, proper quotation of such a string requires to write a fully fledged f-string parser, in which case the whole problem solves itself. Don't ask how to use X to do Y. Ask how to do Y. Good advice. Exactly. As I have shown, asking how to use f-strings to achieve this is simply not suitable, and there's no useful way to discuss other than to argue semantics. If we had a GOAL to discuss, we could find much better options. I was not asking how to use f-strings. I was asking to evaluate a string *as if it were* an f-string. Those are two completely different things which you entirely ignored. In other words, if there were a magic function: evalfstring(s, x = x) That would have been the ideal answer. There does not seem to be one, however. So I'm back to silly workarounds. Cheers, Johannes -- https://mail.python.org/mailman/listinfo/python-list
Re: Evaluation of variable as f-string
Am 28.01.23 um 02:51 schrieb Thomas Passin: This is literally the version I described myself, except using triple quotes. It only modifies the underlying problem, but doesn't solve it. Ok, so now we are in the territory of "Tell us what you are trying to accomplish". And part of that is why you cannot put some constraints on what your string fragments are. The example I gave, copied out of your earlier message, worked and now you are springing triple quotes on us. It works in this particular case, yes. Just like the example I gave in my original case: eval("f'" + s + "'") "works" if there are no apostrophes used. And just like eval("f\"" + s + "\"") "works" if there are no quotation marks used. I don't want to have to care about what quotation is used inside the string, as long as it could successfully evaluate using the f-string grammar. Stop with the rock management already and explain (briefly if possible) what you are up to. I have a string. I want to evaluate it as if it were an f-string. I.e., there *are* obviously restrictions that apply (namely, the syntax and semantics of f-strings), but that's it. Best, Johannes -- https://mail.python.org/mailman/listinfo/python-list
Re: Usenet vs. Mailing-list (was: evaluation question)
On 2023-01-28, Peter J. Holzer wrote: > On 2023-01-27 21:04:58 +, Ben Bacarisse wrote: >> It looks like you posted this question via Usenet. comp.lang.python is >> essentially dead as a Usenet group. It exists, and gets NNTP versions >> of mail sent to the mailing list, but nothing posted to the group via >> NNTP get send on the mailing list. > > This is wrong. I did get Muttley's any your postings via the > mailing-list. Yes, it's certainly false. I only ever post via the newsgroup, and I can see my postings reach the list because they appear in the list archive on the web. https://mail.python.org/pipermail/python-list/ -- https://mail.python.org/mailman/listinfo/python-list
Re: evaluation question
mutt...@dastardlyhq.com wrote: On Sat, 28 Jan 2023 14:22:01 +1300 dn wrote: Do you know about the Python REPL? Haven't learnt the acronyms yet. REPL stands for "Read Evaluate Print Loop". It basically refers to the interactive interpreter, which reads input you type, evaluates it, prints the result, and loops (repeatedly does that). An interesting point from your examples is that the output from the first two comes from different steps in that loop. >>> eval("1+1") 2 Here, the E (evaluation) step runs eval("1+1"), which returns 2. The P (print) step then prints that result. If this was in a script, you wouldn't see any output, and the statement is pretty much useless - you'd need to assign the result to a variable or explicitly print it. >>> eval("print(123)") 123 Here, the E step runs eval("print(123)"), which prints 123 and returns None. The P step doesn't print anything if the result is None. You'd still see that output if this was in a script. Using eval in those examples is pretty pointless, since: >>> 1+1 >>> print(123) would produce the same results - but of course they were just simple examples. -- Mark. -- https://mail.python.org/mailman/listinfo/python-list
Re: evaluation question
On 1/27/2023 9:37 AM, mutt...@dastardlyhq.com wrote: Hi This is probably a dumb newbie question but I've just started to learn python3 and eval() isn't behaving as I'd expect in that it works for some things and not others. eg: eval("1+1") 2 eval("print(123)") 123 eval("for i in range(1,10): i") Traceback (most recent call last): File "", line 1, in File "", line 1 for i in range(1,10): i ^ SyntaxError: invalid syntax Why did the 3rd one fail? Does it not handle complex expressions? Thanks for any help This might -- or might not -- be useful: eval( "print( [i for i in range(1, 10)] )" ) It prints a list, but you probably knew that: [1, 2, 3, 4, 5, 6, 7, 8, 9] Louis -- https://mail.python.org/mailman/listinfo/python-list
Re: evaluation question
On Sat, 28 Jan 2023 14:22:01 +1300 dn wrote: >On 28/01/2023 05.37, mutt...@dastardlyhq.com wrote: >> This is probably a dumb newbie question but I've just started to learn >> python3 and eval() isn't behaving as I'd expect in that it works for >> some things and not others. eg: >> > eval("1+1") >> 2 > eval("print(123)") >> 123 > eval("for i in range(1,10): i") >> Traceback (most recent call last): >>File "", line 1, in >>File "", line 1 >> for i in range(1,10): i >>^ >> SyntaxError: invalid syntax >> >> Why did the 3rd one fail? Does it not handle complex expressions? > >eval() is very powerful, and therefore rather dangerous in the risks it >presents. > >Thus, seems a strange/advanced question for a "newbie" to be asking. YMMV! Well ok, new-ish :) >Do you know about the Python REPL? Haven't learnt the acronyms yet. >If you open python within a terminal, each of the three >expressions/compound-statements listed will work, as desired, without >eval(). Umm, yeah, thats kind of obvious isn't it? -- https://mail.python.org/mailman/listinfo/python-list
Re: evaluation question
On Fri, 27 Jan 2023 21:04:58 + Ben Bacarisse wrote: >mutt...@dastardlyhq.com writes: > >> Hi > >It looks like you posted this question via Usenet. comp.lang.python is >essentially dead as a Usenet group. It exists, and gets NNTP versions >of mail sent to the mailing list, but nothing posted to the group via >NNTP get send on the mailing list. I prefer Usenet and dislike mailing >lists but that just means I can't really contribute to this "group" > >The "python-list" an an excellent resource (if you like the email >interface) and you can subscribe here: > >https://mail.python.org/mailman/listinfo/python-list>, > >> This is probably a dumb newbie question but I've just started to learn >> python3 and eval() isn't behaving as I'd expect in that it works for >> some things and not others. eg: >> > eval("1+1") >> 2 > eval("print(123)") >> 123 > eval("for i in range(1,10): i") >> Traceback (most recent call last): >> File "", line 1, in >> File "", line 1 >> for i in range(1,10): i >> ^ >> SyntaxError: invalid syntax >> >> Why did the 3rd one fail? Does it not handle complex expressions? > >It handles only expressions, and "for i in range(1,10): i" is not an >expression. You can use > exec("for i in range(1,10): i") Ok, thanks. -- https://mail.python.org/mailman/listinfo/python-list
Re: Usenet vs. Mailing-list (was: evaluation question)
On Sat, 28 Jan 2023 15:30:59 +0100, "Peter J. Holzer" declaimed the following: >On 2023-01-27 21:04:58 +, Ben Bacarisse wrote: >> mutt...@dastardlyhq.com writes: >> >> > Hi >> >> It looks like you posted this question via Usenet. comp.lang.python is >> essentially dead as a Usenet group. It exists, and gets NNTP versions >> of mail sent to the mailing list, but nothing posted to the group via >> NNTP get send on the mailing list. > >This is wrong. I did get Muttley's any your postings via the >mailing-list. > I had been tempted to ask when the list<>newsgroup link had changed, since it hadn't been announced... Now -- last time I checked the gmane server says posting is prohibited. I used to use gmane as it retrieved directly from the mailing list (which has been filtered from much spam) and not Usenet (and its open spam problem). -- Wulfraed Dennis Lee Bieber AF6VN wlfr...@ix.netcom.comhttp://wlfraed.microdiversity.freeddns.org/ -- https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?
Jach Feng 在 2023年1月22日 星期日上午11:11:22 [UTC+8] 的信中寫道: > Fail on command line, > > e:\Works\Python>py infix2postfix.py "-4^2+5.3*abs(-2-1)/2" > usage: infix2postfix.py [-h] [infix] > infix2postfix.py: error: unrecognized arguments: -4^2+5.3*abs(-2-1)/2 > > Also fail in REPL, > > e:\Works\Python>py > Python 3.8.8 (tags/v3.8.8:024d805, Feb 19 2021, 13:08:11) [MSC v.1928 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import argparse > >>> parser = argparse.ArgumentParser(description='Convert infix notation to > >>> postfix') > >>> parser.parse_args("-4^2+5.3*abs(-2-1)/2") > usage: [-h] > : error: unrecognized arguments: - 4 ^ 2 + 5 . 3 * a b s ( - 2 - 1 ) / 2 > > Just can't figure out where is wrong!? > > --Jach I have to admit that I don't know the background upon which the argparse was built. The good side is that I don't carry its historical knowledge ( or burden?), that's why I can use it in a new way which may make someone feel uneasy. The reason I am still keep on using argparse on this "one positional argument only" CLI app is that I can't see what advantage I can get when writing code to handling sys.argv directly for the following two situations, - e:\Works\Python>py infix2postfix.py usage: infix2postfix.py [-h] infix infix2postfix.py: error: the following arguments are required: infix e:\Works\Python>py infix2postfix.py -h usage: infix2postfix.py [-h] infix Convert infix notation to postfix positional arguments: infix Put equations in quote if there is space in it and separate each one with a comma, ie. "-4^2+5.3*abs(-2-1)/2, abs(Abc)*(B+C)/D, (-3) * sqrt(1-(x1/7)*(y1/7)) * sqrt(abs((x0-4.5)/(y0-4)))" optional arguments: -h, --help show this help message and exit - comparing with code using the argparse below, import argparse sample = "-4^2+5.3*abs(-2-1)/2, abs(Abc)*(B+C)/D, (-3) * sqrt(1-(x1/7)*(y1/7)) * sqrt(abs((x0-4.5)/(y0-4)))" parser = argparse.ArgumentParser(description='Convert infix notation to postfix') parser.add_argument('infix', help='Put equations in quote if there is space in it and separate each one with a comma, ie. "{}"'.format(sample)) import sys if len(sys.argv) > 1 and not '-h' in sys.argv: sys.argv.insert(1, '--') args = parser.parse_args() -- https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?
Jach Feng wrote: Jach Feng 在 2023年1月22日 星期日上午11:11:22 [UTC+8] 的信中寫道: Fail on command line, e:\Works\Python>py infix2postfix.py "-4^2+5.3*abs(-2-1)/2" usage: infix2postfix.py [-h] [infix] infix2postfix.py: error: unrecognized arguments: -4^2+5.3*abs(-2-1)/2 Also fail in REPL, e:\Works\Python>py Python 3.8.8 (tags/v3.8.8:024d805, Feb 19 2021, 13:08:11) [MSC v.1928 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. import argparse parser = argparse.ArgumentParser(description='Convert infix notation to postfix') parser.parse_args("-4^2+5.3*abs(-2-1)/2") usage: [-h] : error: unrecognized arguments: - 4 ^ 2 + 5 . 3 * a b s ( - 2 - 1 ) / 2 Just can't figure out where is wrong!? --Jach I have to admit that I don't know the background upon which the argparse was built. The good side is that I don't carry its historical knowledge ( or burden?), that's why I can use it in a new way which may make someone feel uneasy. If you can use it in the way you want, that's great. I thought you were asking here because you *couldn't* use it the way you want. You're writing a command-line application. Your users are either already familiar with the conventions of command-line applications, or they'll soon need to be. If your application supports options beginning with a "-" (which is what argparse gives you, even if only the default "-h" and "--help" options are actually valid), and you also need to be able to pass positional arguments which begin with a "-", you need some way for the user to indicate whether any particular argument is an option or positional. Using "--" to indicate that all subsequent arguments are positional, not options, is a common convention. Some of your users might already be familiar with that convention from other command-line tools. By using the same convention, you'd be making it easier for them to use yours. Others might not already be familiar with the convention, but by being consistent with other tools you'd still be helping them when they eventually do come across it elsewhere. You can always include an explanation of using "--" in your usage output or other documentation. Apart from dealing with how to pass an argument beginning with "-", your users will also likely have to deal with the features of whichever shell they're using, which you have no control over. For example, it's quite common to need to enclose an argument in quotes if it contains spaces. It may also be necessary to use quotes if certain special characters are used, such as "*", "?" or "$" (perhaps "%" on Windows). The reason I am still keep on using argparse on this "one positional argument only" CLI app is that I can't see what advantage I can get when writing code to handling sys.argv directly for the following two situations, - e:\Works\Python>py infix2postfix.py usage: infix2postfix.py [-h] infix infix2postfix.py: error: the following arguments are required: infix e:\Works\Python>py infix2postfix.py -h usage: infix2postfix.py [-h] infix Convert infix notation to postfix positional arguments: infix Put equations in quote if there is space in it and separate each one with a comma, ie. "-4^2+5.3*abs(-2-1)/2, abs(Abc)*(B+C)/D, (-3) * sqrt(1-(x1/7)*(y1/7)) * sqrt(abs((x0-4.5)/(y0-4)))" optional arguments: -h, --help show this help message and exit - comparing with code using the argparse below, import argparse sample = "-4^2+5.3*abs(-2-1)/2, abs(Abc)*(B+C)/D, (-3) * sqrt(1-(x1/7)*(y1/7)) * sqrt(abs((x0-4.5)/(y0-4)))" parser = argparse.ArgumentParser(description='Convert infix notation to postfix') parser.add_argument('infix', help='Put equations in quote if there is space in it and separate each one with a comma, ie. "{}"'.format(sample)) import sys if len(sys.argv) > 1 and not '-h' in sys.argv: sys.argv.insert(1, '--') args = parser.parse_args() Personally, I do quite often use argparse even for simple cases, partly because it produces nice usage details, and deals with wrapping the output to whatever width the console is. But I work with it rather than against it, and accept that a "--" is needed if a positional argument starts with a "-". I notice you explain the need to enclose the equation in quotes if it contains spaces. That's not even a feature of your application, but of the shell used to call it. So why so much objection to explaining the need for "--"? Depending on the shell, there are other cases where quoting might be needed, e.g. if the equation includes a "*" or "?" and happens to look like a pattern matching files in the current directory (most shells I've used pass the pattern unchanged if it doesn't match any files). In bash, if a "$" is used I'd need to enclose that in 'single quotes' (can't even use "double quotes" for that one). You can't really expect to document all that sort of thing, because it depends on which shell the user
Re: RE: RE: bool and int
you have your reasons, and I was tempted to stop there, but... I have to pick this... On 1/26/2023 10:09 PM, avi.e.gr...@gmail.com wrote: You can often borrow ideas and code from an online search and hopefully cobble "a" solution together that works well enough. Of course it may suddenly fall apart. also carefully designed systems that are the work of experts may suddenly fall apart. Thank you for all the time you have used to address the points I raised. It was interesting reading. Dino -- https://mail.python.org/mailman/listinfo/python-list
Re: bool and int
On Fri, 27 Jan 2023 21:35:11 -0800 (PST), Grant Edwards wrote: > In Unix shells, a return code of 0 is true and non-0 is false. That carries over to some C functions like strcmp() although it's more complex. strcmp() returns the value of subtracting the nth character of string b from string a if the value is not 0. For matching strings, the result is 0 for all character positions. This plays nicely with sorting functions but naive programmers assume it's a boolean and strcmp("foo", "foo") should return 1 or true when the strings match. Returning 0 for success gives you much more latitude in return values. -- https://mail.python.org/mailman/listinfo/python-list
Re: logically Boolean
On 29/01/2023 09.28, Chris Angelico wrote: The REAL boolean is the friends we made along the way? By REAL did you mean float - True or False? (for the FORTRAN-free: https://fortranwiki.org/fortran/show/real) -- -- Regards, =dn -- https://mail.python.org/mailman/listinfo/python-list
Re: logically Boolean
On Sun, 29 Jan 2023 at 04:33, wrote: > The right answer is that the question is too simple. It is what YOU want it > to be in your situation. And it is also what the LANGUAGE designers and > implementers have chosen within their domain. The REAL boolean is the friends we made along the way? ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Non int Boolean
If someone really really wants a non-int Boolean, it is easy to implement. 5 or 6 lines, depending on whether you count the import statement: from enum import Enum class MyBool(Enum): TRUE = 42 FALSE = 54 def __bool__(self): return self == MyBool.TRUE # # testing # mytrue = MyBool.TRUE try: print(int(mytrue)) #this fails except TypeError as te: print(te) asbool = bool(mytrue) if mytrue: print("yep") myfalse = MyBool.FALSE if myfalse: print("nope") --- I would never use such a thing, and I would be annoyed if I can across code that did. As has been said (beaten to death?) Python has an existing well-understood boolean type. -- https://mail.python.org/mailman/listinfo/python-list
Unix / linux programs
The Unix convention is 0 means everything went well, and non-zero means something else happened. Here’s a contrived example of a bash wrapper around GNU tar. By contrived I mean it works but I would not use it in practice … I’d just use tar directly or use the Python tarfile module if I wanted finer grain control of the process. #!/bin/bash if [ $# -lt 2 ]; then echo "Usage: $0 [tar] [directory to compare]" fi tar --diff -f $1 $2 2>/dev/null r=$? if [ $r -eq 0 ]; then echo $1 has $2 in it, unmodified elif [ $r -eq 1 ]; then echo $1 does not have $2 in it unmodified elif [ $r -eq 2 ]; then # maybe do more tests here? echo There is a problem with $1 or with $2 else echo "Other error $r" fi Incidentally, I found the man page installed on Ubuntu20.04 for tar is out of date. tar returns 64 if doesn’t like the command line arguments. Nothing works until it is tested. -- https://mail.python.org/mailman/listinfo/python-list
logically Boolean
The topic has somewhat modified to asking what is a BOOLEAN. The right answer is that the question is too simple. It is what YOU want it to be in your situation. And it is also what the LANGUAGE designers and implementers have chosen within their domain. Mathematically, as part of classical logic, there is a concept of having two sets with the union of the two being a null set. The sets are disjoint and in some cases, cover all possibilities and in other cases the possibilities are narrowed so that just two distinct groupings remain. Using 0 and 1 makes sense for a binary bit, albeit in either order for True versus False. No other numbers can be stored in a single binary digit so this is a trivial but useful use of Booleans in some languages. In hardware or storage mediums, there are not literal zeroes or ones. You can have a high or low value or a magnetic field or spin or whatever you want to implement it, and sometimes it fails anyway and you get indeterminate values or a bit seems to flip. That is an implementation detail but Boolean logic remains a mathematical concept. UNIX programs did not return a Boolean value on exit so that discussion is a tad off the point. They returned a STATUS of sorts. Mostly the status was zero for all forms of success and you could signal many forms of failure using any other number. But I can imagine designing a program like grep to return 0 if nothing was found but the program did not fail, and a positive number up to some limit that specified how many lines matched and perhaps -1 or other numbers on failure. A return status need not be seen as Boolean, albeit in my made-up example, any non-zero exit status up to the limit would be in the set of SUCCESS and -1 or whatever would be in the set for FAILURE. Consider how a Python function can return OR throw an error. Many different errors can be thrown and some propagate up from deeper levels if not caught and handled. Generally success simply means no errors BUT you can also design a function that throws various success "errors" and indirectly returns one of several kinds of values in the payload, as well as errors meant to be treated as bad. Heck, you can have some errors be warnings and the caller of the function may have to call it from a "try" and specify what to catch and how to deal with it. I repeat, not everything must be Boolean when it comes to status types of things. As noted, many other schemes have been used to represent a Boolean variable. And given some implementations, something emerges that can confuse some people. Grant mentioned even/odd. On most machines this simply means you can safely ignore a longer clustering of bits such as with a 32-bit integer and simply examine the least significant bit which determines if it is even or odd. Heck, you can even store other useful info in the remaining bits, if you wish. As has been said repeatedly, it does not matter what the OP expects, as many implementations are possible including some that do not follow the above suggestions. Much of my work has included other possibilities often using data that is not always able to be analyzed in a truly Boolean fashion. Modern Programming languages have to grapple with items that look like they can have three or more values. I mean you can have a variable that can be TRUE or FALSE but also one of many forms of Not Available or more. In a language like R, their version of Boolean can have a value of NA but actually in some contexts you have to specify which kind of NA such as NA_integer_ or NA_character_ so obviously a vector of Booleans cannot be implemented using a single bit for each. I have seen packages that can import data with many kinds of missing values as there are other programs that allow you to tag missing values to mean things like "missing: child did not show up to take test" or "missing: test not completed, will re-test" or "missing: caught cheating" or "missing: identity of test taker not verified" and so on. I helped with one such package to create a type within R that does not discard the other info so it supports multiple NA variants while at the same time it can be processed as if every NA was the same. Python has concepts along the same lines such as np.nan so there has to be a way of storing data with perhaps a wrapper around things that can specify if the contents are what is expected, or maybe something else. And I won't get into fuzzy logic. But just plain classical Boolean logic is a mathematical concept that can be expressed many ways. Some of the ways in python look compatible with integers but that was a design choice. If they had chosen to store a character containing either "T" or "F" then perhaps they would allow Booleans to be treated as characters and let them be concatenated to strings and so on. -Original Message- From: Python-list mailto:python-list-bounces+avi.e.gross=gmail@python.org> > On Behalf Of Grant Edwards Sent:
Usenet vs. Mailing-list (was: evaluation question)
On 2023-01-27 21:04:58 +, Ben Bacarisse wrote: > mutt...@dastardlyhq.com writes: > > > Hi > > It looks like you posted this question via Usenet. comp.lang.python is > essentially dead as a Usenet group. It exists, and gets NNTP versions > of mail sent to the mailing list, but nothing posted to the group via > NNTP get send on the mailing list. This is wrong. I did get Muttley's any your postings via the mailing-list. (I also get Stefan Ram's postings despite his "no distribution outside of Usenet" header). hp -- _ | Peter J. Holzer| Story must make more sense than reality. |_|_) || | | | h...@hjp.at |-- Charles Stross, "Creative writing __/ | http://www.hjp.at/ | challenge!" signature.asc Description: PGP signature -- https://mail.python.org/mailman/listinfo/python-list
Re: Evaluation of variable as f-string
On 2023-01-27 21:31:05 +0100, Johannes Bauer wrote: > > But if you really REALLY know what you're doing, just use eval() > > directly. > > I do, actually, but I hate it. Not because of the security issue, not > because of namespaces, but because it does not reliably work: > > >>> s = "{\"x\" * 4}" > >>> eval("f'" + s + "'") > '' That's exactly the result I expected. What did you expect? hp -- _ | Peter J. Holzer| Story must make more sense than reality. |_|_) || | | | h...@hjp.at |-- Charles Stross, "Creative writing __/ | http://www.hjp.at/ | challenge!" signature.asc Description: PGP signature -- https://mail.python.org/mailman/listinfo/python-list
Re: Evaluation of variable as f-string
On 2023-01-27 21:43:09 +0100, Johannes Bauer wrote: > x = { "y": "z" } > s = "-> {x['y']}" > print(s.format(x = x)) > Traceback (most recent call last): > File "", line 1, in > KeyError: "'y'" > > This. Does. Not. Work. > > I want to pass a single variable as a dictionary and access its members > inside the expression. You can do that (see other responses), but you can't have arbitrary Python expressions inside a format string. It works with f-strings because f-strings are a compiler construct. The f-string never exists at run-time. Instead the compiler transforms f"-> {x['y']}" into the equivalent of "-> " + format_value(x["y"]) + "" So either you need to pass it to the Python compiler (via eval), or you need to implement enough of a Python parser/interpreter to cover the cases you are interested in. The latter might be an interesting exercise, but I would suggest looking at existing template engines like Jinja2 for production purposes. hp -- _ | Peter J. Holzer| Story must make more sense than reality. |_|_) || | | | h...@hjp.at |-- Charles Stross, "Creative writing __/ | http://www.hjp.at/ | challenge!" signature.asc Description: PGP signature -- https://mail.python.org/mailman/listinfo/python-list
Re: Evaluation of variable as f-string
On 2023-01-27 20:56:49 -0500, Thomas Passin wrote: > On 1/27/2023 5:10 PM, Christian Gollwitzer wrote: > > Am 27.01.23 um 21:43 schrieb Johannes Bauer: > > > x = { "y": "z" } > > > s = "-> {x['y']}" > > > print(s.format(x = x)) > > > Traceback (most recent call last): > > > File "", line 1, in > > > KeyError: "'y'" > > > > > > This. Does. Not. Work. > > > > It's because "you're holding it wrong!". Notice the error message; it ^^^ > > says that the key 'y' does not exist. [...] > > In [1]: x = { "y": "z" } > > In [2]: s = "-> {x[y]}" > > In [3]: print(s.format(x = x)) > > -> z > > In [4]: > > Oops, that's not quite what he wrote. > > You: s = "-> {x[y]}"# Works > Him: s = "-> {x['y']}" # Fails That was the point. hp -- _ | Peter J. Holzer| Story must make more sense than reality. |_|_) || | | | h...@hjp.at |-- Charles Stross, "Creative writing __/ | http://www.hjp.at/ | challenge!" signature.asc Description: PGP signature -- https://mail.python.org/mailman/listinfo/python-list