12 ms·
No-op statements syntactically valid only since Python X.Y
- RektBoy 4y agosys.version_info ???
- tyingq 4y agoTry it with a single file python script, and you'll see the problem.
- deleted 4y ago[deleted]
- SCLeo 4y agoIn my experience, the hardest part is figuring out what is the minimum version of python your script requires. I usually just put down the version I am using in the readme, but if it is enforced, it probably should be more accurate.
- ufo 4y agoAfter looking at their 3.11 example, I wonder... Why can't we put a function definition in the same line of an if statement? if True: def f(x): return x Is this just because Python doesn't want to encourage extreme terseness? Or is it also because there would be problems or grammar ambiguities were this to be allowed?
- deleted 4y ago[deleted]
- jwilk 4y agohttps://docs.python.org/3/reference/compound_stmts.html https://docs.python.org/3/reference/compound_stmts.html "Only the [indented] form of a suite can contain nested compound statements; the following is illegal, mostly because it wouldn’t be clear to which if clause a following else clause would belong: if test1: if test2: print(x) "
- aidenn0 4y agoIt would be interesting to see the reverse; I've definitely had python code break in interesting when upgrading the interpreter.
- jwilk 4y agohttps://twitter.com/dalkescientific/status/1457940309636272128 https://twitter.com/dalkescientific/status/14579403096362721... has a few examples, most of them from the 2.X era. I doubt there's much more. I've been using something similar to exec '' # Python 2.X is required in a few projects stuck on Python 2.
- Iv 4y agoIt is both cute and horrifying to realize that Python has no builtin functionality for this.
- eloff 4y agosys.version_info I'm not sure why this guy is doing it the hard way.
- Iv 4y agoBecause, as mentioned several times in this discussion, if you give a python3 file to a python2 interpreter, you will get a SyntaxError even before the first line of the script runs. This is a way o ensuring the correct python version is used and to display a clear error message next to it.
- deleted 4y ago[deleted]
- haihaibye 4y agoThese are cute, but I disagree with the suggested use case of putting them at the start of files to throw syntax errors to check Python versions. Just check values in sys.version_info then throw an exception, it's so much more obvious what you're doing.
- teraflop 4y agoIf the source file contains syntax that is invalid on the user's Python version, then your code that's supposed to check the version and throw a helpful exception will never run. Instead the Python interpreter will throw a syntax error the first time it tries to parse something it doesn't recognize, and that syntax error may not make it obvious what the problem is.
- haihaibye 4y agoOk, that's a real problem, maybe we need a PEP for a minimum version in the header eg: # -*- python >= 3.1 -*- The trouble is, that wouldn't work on the old versions!
- tyingq 4y ago>The trouble is, that wouldn't work on the old versions! Yeah, a bit late to address the issue. Would have been helpful in the 2->3 transition.
- haihaibye 4y agoThe best time to adopt it was in 2.X, the second best time is now....
- indrora 4y agoPyPA has basically done that with pyproject.toml/Pipfile and pyenv.
- klysm 4y agoThis is a good point, but can’t you do it in __init__.py? I thought that ran first
- rtpg 4y agoSpeaking of this kind of check... recently I have been trying to set up some scripts that could run on Mac with "nothing installed". I had been opting for Python (even using `urllib` to avoid having `requests` as an option) and... a good chunk of people ended up hitting weird errors with SSL certs. I know there are probably other answers (I guess writing binaries in Go?), but given how nice Python is for glue code when it works, I do wish for something like `python --config-file pyproject.toml my-script.py` that would figure out requirements, install those "somewhere", ensure the right python version (installing if necessary) and then run the script in a consistent environment (PYTHONPATH being reset, for example). I know there's a lot of tools for packaging Python code into their own binaries, but I think we could probably get pretty far with some built-in "install and run" tooling that doesn't start with "decide where to put a virtualenv"
- tyingq 4y ago>trying to set up some scripts that could run on Mac with "nothing installed" Perl still comes with MacOS 12.3. And Perl would be a decent language to bootstrap a working Python with working certificates, etc. Though Apple has said all scripting languages will be removed from the default install eventually. "Scripting language runtimes such as Python, Ruby, and Perl are included in macOS for compatibility with legacy software. Future versions of macOS won’t include scripting language runtimes by default, and might require you to install additional packages. If your software depends on scripting languages, it’s recommended that you bundle the runtime within the app." >I guess writing binaries in Go? Then you get the fun of signing, or README language to guide the user around adding an exception. They sure are making bootstrapping hard. I wish they would pick at least one stable scripting environment to bundle...lua maybe?
- zbentley 4y agoDoes perl have a built in HTTP client? The author wanted to hit a URL, and if I recall perl didn't support that natively (I last used it professionally in 5.16 though, so I may be out of date). If the state of the art in Perl is still "shell out to curl or whatnot" then that is really not portable or stable compared to Python's included urllib--SSL errors or not.
- seniorsassycat 4y agoHow do these work for very old versions of python? $ python3.5 since-3.6.py File "since-3.6.py", line 1 0_0 # Python >= 3.6 is required This error means python 3.5 knows the syntax is valid in 3.6 which is plausible, but why would `python2.4 since-3.6.py` have a useful error message? Edit: the comment is included in the source and python prints the whole line 0_0 # use python 3.6 or greater
- mlyle 4y agoPython 3.5 doesn't know the syntax is valid in 3.6. It knows it's invalid python 3.5 syntax, and then throws the exception. We see the comment in the process. % python2 since_3.6.py File "since_3.6.py", line 1 0_0 # Python >= 3.6 is required ^ SyntaxError: invalid syntax % python2 --version Python 2.7.18
- anonymoushn 4y agoThe error message is a comment in the code, so python2.4 just has to print the line with the syntax error
- aaronmdjones 4y ago> This error means python 3.5 knows the syntax is valid in 3.6 It doesn't. This relies on the interpreter printing the whole line that contains a syntax error, including the comment on it.
- kazinator 4y agoBut that's not an error message; it's just a copy of the offending line in the file! $ python2 Python 2.7.17 (default, Feb 27 2021, 15:10:58) [GCC 7.5.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 0_0 # Python >= 3.6 is required File "<stdin>", line 1 0_0 # Python >= 3.6 is required
- kevsim 4y agoThat's the point. Since it can't actually parse the file, this is as good as it gets. It at least gets something on the screen that says "Python >= 3.6 is required" which is better than nothing.
- alanbernstein 4y agoInteresting. Links to relevant PEPs in comments could be useful.
- mlyle 4y agoThe point is to print a message with the required python version when parsing fails, not to tell you about this specific feature that doesn't work.
- jamesfinlayson 4y agoI'd be interested to know regardless - the @0 in the Python 3.9 example has me stumped. Maybe it's a decorator but I don't think so. It doesn't look like matrix multiplication either.
- alanbernstein 4y agoYep, that was the example that prompted my suggestion. Special syntax can be hard to search for.
- henbruas 4y agoIt is indeed a decorator. It's relying on https://peps.python.org/pep-0614/ https://peps.python.org/pep-0614/
- carapace 4y agoThanks for posting that, I was puzzled too. - - - - I can't help myself. The example in the PEP: buttons = [QPushButton(f'Button {i}') for i in range(10)] # Do stuff with the list of buttons... @buttons[0].clicked.connect def spam(): ... ... seems silly to me, I would have done something like: connect_button = lambda n: buttons[n].clicked.connect @connect_button(0) def spam(): ... I was a huge Python fan but these days I really feel that Python is being improved to death.
- 4y ago
- usr1106 4y agoI learned Python probably over 15 years ago. Haven't used it very much and certainly not followed all the news. I remember back then it was said the design philosphy was something like there should be one obvious way to code something correctly. In opposite to Perl where the philosohpy was that human thoughts can take weird ways and you should be able to put your thoughts to code directly. (Both characterizations from memory.) Today I hear little from Perl. And with new syntax added to Python in every version I start to wonder how far away Python is drifting away from that original characterization above.
- planckscnst 4y agoI don't ever think Python has lived up to that tenet. If they did, then there wouldn't be a million pull requests with comments saying something to the effect of "the pythonic way to do this is..." or "pipXYZ says you should/shouldn't..."
- Aloha 4y agoAt some point those two philosophies cross over, that's where you end up with bash or even php, there are several right ways, and several wrong ways, and all of them work.
- noobermin 4y agoOne way was never going to work, ever. No real substantive platform of any kind will ever have one way to do something. May be if you're a literalist, there can sometimes be an "obvious way" to do something with emphasis on "obvious," but beyond that, the moment you have more than one library in the ecosystem that does a similar thing, you no longer can do something "one way." I'm not sure if today that really matters though. I will admit I don't know much about Perl but Perl's death vs Python's life probably might have some influence from design choices but a lot of it just has to do with the libraries you have access to with Python. I know as a scientist, Python is the game in town, that has more to do with why I use it than design.
- xenophonf 4y agoPerl's popularity waned because of the whole Perl 6 fiasco, which stole lots of energy from Perl 5, offered no migration path from Perl 5, and eventually evolved into a completely different language. As a result, Perl 5 development stalled, and developers went elsewhere. I personally stopped writing new Perl code around 2005-2006 after learning Python 2 in 2003-2004 (when I was doing a lot of Zope/Plone hacking). I think Python 3 almost killed Python, too, and for the same reasons. The developers behind 2to3 saved the community, in my opinion, as did the folks who made the painful decision to publish a Python 2 end-of-life date sufficiently far enough into the future that people still using the old runtime had both a sense of urgency and plenty of time to complete their migrations. I finally made the leap to Python 3 around 2016. I'd like to claim that I jumped instead of being pushed, but the reality is that by then, people were developing new stuff I wanted badly on Python 3 exclusively.
- turtledove 4y agoRelying on a mechanism like this is, at best, extremely brittle. Seeing something like this in the wild would be a strong nope from me.
- wongarsu 4y agoBrittle in which way? I wouldn't expect a maintenance release of an old python version to add support for syntax from a newer version, or a new version removing syntax for current syntax (if that happens we are on a new major version and failing is entirely acceptable)
- turtledove 4y agoWhat if someone makes a change to the pattern because they are maintaining the code but don't understand it? What if a future version of Python stops accepting that as valid syntax? It's too clever by half.
- lexicality 4y agoIf python 4 comes along and stops supporting that syntax then it's fairly likely that the rest of the code will be broken too. That doesn't sound like a huge downside to me.
- noobermin 4y agoJust being a little pedantic here, nop usually means actually no operations performed, not just "has no side effects". By this definition, this (6502asm) is also a nop bcc @dummy @dummy: With the special case of an extra cycle just on the off chance the bcc is at the end of the current page. It indeed leaves no side-effects but I don't know if people would really seriously call it a nop
- Karliss 4y agoEven "true" noop instructions then ones generated by writing corresponding opcode in assembly often decode to "no side effect instruction". Something like exchanging register with itself, or adding 0 to register. Modern high performance cpu designs will probably optimize those instructions and not preform the useless no side effect operation, but on simpler cpus extra logic for detecting it and not performing anything might not be worth it. So those noops will actually try to execute the no side effect operation which matches with decoded instruction. Wikipedia has table of them for different architectures https://en.wikipedia.org/wiki/NOP_(code) https://en.wikipedia.org/wiki/NOP_(code)
- MauranKilom 4y agoWell, if you take that into consideration then no nop instruction (of non-zero size) can exist in asm, because they still require advancing EIP (and decoding the instruction).
- dvt 4y agoIf you really need to do this, it should be done like so in some sort of bootstrap file that won't run into parsing/lexing errors: import sys sys.version_info if not sys.version_info[:2] == (3, 1): raise Exception("You need Python >= 3.1") else: from your_module import whatever I really hope no one's seriously using this repo to get any ideas.
- Starlevel001 4y agoOr just put a ``python_requires`` in your setup.cfg.
- ezfe 4y agoAnd now I need a setup.cfg
- aeonflux 4y agoAs already pointed out, whole file is parsed before it's actually run. If you have any unsupported syntax, you will get a SyntaxError without your message being printed at all. What would be your suggestion to do this for single file scripts?
- deleted 4y ago[deleted]
- dvt 4y agoTurn them into two-file scripts, or have a readme, or just let it fail because supporting every single version of Python is insane. This whole thing is just a classic case of the XY Problem[1]: a solution looking for a problem. [1] https://xyproblem.info/ https://xyproblem.info/
- robertlagrant 4y agoIt's not an XY problem. That describes a mismatched problem-solution pair. Not the case here.
- deleted 4y ago[deleted]
- msla 4y agoThis reminds me of how people used to use machine code which exposed and tested for slight differences in processors to detect x86 processor versions before CPUID: http://www.rcollins.org/ddj/Sep96/Sep96.html http://www.rcollins.org/ddj/Sep96/Sep96.html
- lifthrasiir 4y agoOr feature detection in web development, which made `document.all` an exotic object (ECMAScript speak) in modern browsers [1]. [1] https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
- kzrdude 4y agoInteresting! So if we didn't have CPUID we'd have some open source assembler only library called x86_cpu_guesser or so
- deleted 4y ago[deleted]
- motbus3 4y agoi wonder if that's a great idea. if for any reason the syntax get ported to older versions it will be unlucky to rely on it. seems more secure to check python version normally.
- akullpp 4y agoAh, the Zen of Python: Make simple things unnecessarily complex and put a thin veil of ideological reasoning on top of it.