@@xravenx24fe the type of a* is the key point here. uint8 a* and ulongint64 a* are different (uint8 and ulongint64 for clarity, char, int and long int being non standard)
C#, C++, the same. I have complained that "you can write FORTRAN" in any language. I felt physically sick when I saw the code I was inheriting. I threw it all away. They couldn't even use the IDE to PEP 8 the stuff.
Yeah, it is mind boggling that people create their own methods instead of using Dunders. The entire idea of good Python is to reuse the most amount of built-ins
A lot of the code that runs the service I'm on the infra team for is Python written like Java, wrappers for stuff in standard python libraries but now with longer names, and so much nested inheritance you'll want to die trying to figure out what a single line of code even does sometimes. Everyone on the infra team hates it with a fiery passion.
@@kademcgill2599 Too much nested inheritance is bad in any language. In fact just too much nesting in general. The everything happens somewhere else philosophy that leads to incomprehensible code.
How the entire room wasn't just erupting in laughter the whole talk long! I was convinced you must have given this presentation over Zoom or something up until the end.
Nice spot - our original live recording of the talk had very poor audio, so we rerecorded it in-person a few weeks later. The clapping is real though, just from the first session!
14:55 "One is just a module, there's nothing funny going on here" is delivered just perfectly while I'm still dying of laughter over the "fuckit" module lmaoooooooo
It is not really a paradox, since variables/pointers/references/promises in a programming language have a number associated with them that directly identifies them instead of their identity being driven by their components/properties, so being self-referential is a property of the meta-language that allows you to interpret statements as being self-referential when actually all they are doing is concerning numbers. e.g. [[...]] is really the pure tuple of number and set (a,{a}) (where a is the the number that identifies the object) not a set that contains itself And since sets can be infinite, and in particular there are more of them than there are natural numbers, we can't assign a number to every set, so this can't be used to resolve Russel's paradox for actual sets, and if we try to assign a number to every formula we have to contend with at least one of incompleteness or undecidability- not enough to describe every set.
Import replacement is super useful in large codebases because it enables aliasing two import paths to the same package. That lets you move/rename packages without doing it as a single monolithic change.
Just seeing the 'fuckit' library made this worth the watch. For anyone wondering there is a context manager that can do the same thing, but it's not as funny.
While not as nuanced as pretty much any point made in this talk, I'll join in and share my personal favorite "python wat?" entry. This one has the added bonus of being something a programming polyglot might actually run into and have an existential crisis over. Due to the way it handles scope, the _lambda_ expression does not support true closures. But python will try its absolute best to _pretend_ that it does. That means that depending on usage, variables shared across closures will influence each other seemly through pure magic if you're expecting an actual closure. [(lambda x: x + y) for y in range(10)] # has some unfortunate behavior And you can make the above a _lot_ more cursed.
@@KirkWaiblinger I hadn't looked too closely at javascript's scope rules in years, but you inspired me to check it out again. Without digging into the implementation specifics, I can't be certain, but I think these are actually basically identical scoping implementations (at least in the context of closures). You can even play the same trick in both of wrapping the closure declaration in a function to force a fresh variable to be created.
That's not the fault of the closure. Python has perfectly good closures. It happens because of the way the for-loop works: the same loop control variable is re-used across all iterations.
Loved this presentation, and the wry wit with the delivery. imo, a satirical cousin to wat presented by Gary Bernhardt at CodeMash 2012. Thanks for this cursed knowledge.
So good... reminded me of an metaclasses presentation I've seen a while ago, where the presenter tried to show most cursed ways of using them. I was coincidentally thinking about that presentation when YT recommended this to me.
that's a very interesting way to turn any python program into a single line I too wondered once how far you could get by only using one like in python. I was able to make a tic tac toe game without using imports, exec, eval or any complex python features and I was really happy about that but I didn't really have many people to share it with
That's super impressive. The furthest I ever pushed one liners was making a binary search & sort in a single line without using lambda expressions (because I thought they were a cheap way of doing it)
@@identity__thief I did use lambda expressions, but they are still quite limiting since in python you cannot have statements inside lambdas, so no looping or assigning to a variable or even defining variables
@@aioia3885 lambdas themselves are the way to assign variables when one-lining and for for loops you just use list comprehension. I'm curious how he implemented break and continue, unless it's some sort of magic with the if statement?
@@rioghander2te how can you assign variables with lambdas? unless you mean using the parameter of a lambda to instantiate a variable but I'd call that a declaration rather than an assignment for looping I used both list comprehension and recursion, with a trick to avoid call stack overflows
It is theoretically possible to implement everything since the parts from this slide "Requires care" with everything before it is already turing complete
I think I figured it out - the trick is likely the use of to make it look the way it does with cat. appears to be interpreted as a line end by Python, but you can use """ before to write whatever without getting a syntax error, and end the file with a line that only contains """ again, then and then spaces to hide those quotes You can likely hide ansi escape sequences that move the cursor up inside of """ too, allowing you to get rid of the last empty line (in the example the last line does appear to be the Namespaces one, as the prompt seems to add the empty line that is visible, meaning it doesn't belong to the file)
@@codenamelambda ah. i get the magic trick is likely to do with how it is displayed and the code is hidden with '/r' (or '/b'). the very end was really bothering me. like really bothering me. i was like wait, wtf!? stop clapping! why are you ppl clapping? thats impossible. i know python well enough to know the end part is impossible.
@@polyester-pants Nah, there's no shenanigans with escape characters at the end. If you want to figure it out, here's a clue: if you remove the second comment, you get a syntax error as expected, while removing the third comment makes the program do nothing. For a more substantial hint, take a look at Python's PEP 263. Alternatively, if you just want an explanation + the source, see link 2 in the description.
Somehow Andrew Lees' & my last comment were removed; which is strange [and also iirc Andrew Lees' last one also noted comments disappearing].... But yeah; using escape characters is also a possible solution; including getting rid of the last empty line [all you need is the last line having a prefix of at least three characters which is valid Python syntax; even if it would error out at runtime you could always explicitly exit earlier] by moving the cursor up by one line, ending the last triple quotes, rewinding the line with and then having the three (or more) characters to hide those triple quotes again. But yeah, that's not the actual trick employed as Andrew Lees already pointed out - though this trick can do the same and doesn't even require an external file to work; *however* my solution only works with `cat` and similar tools that just regurgitate escape sequences to the console unchanged, so a `less` (without `-R` I believe? That or `-r`) or `bat` etc, as well as any self-respecting text editor, will display the "hidden" code.
I ran into that pretty early in my Python career; the more natural way to get it is "a = []; a.append(a)". Here's a fun fact: if you create two of these things and test them for equality, you get a RecursionError.
fun fact: "a,b = a[:] = b[:] = [0],[0]" makes 2 lists. print(a) shows [[...],[[...],[...]]] and print(b) shows [[[...],[...]],[...]], but a == b, a[0] == b[0] == a, and a[1] == b[1] == b
Do you have the code for your example online? I want to try to figure it out. You're doing some tricky marshal shenanigans, so there are a lot of things you might be doing here.
This is very poetic code. Here, have a poem. If to reach goodly reading, oh book, you proceed with caution, you cannot, by the foolish, be called a stumbling cretin. But if you are too impatient and pull the loaf untimely from the fire and go careening into the hands of the dimwits you'll see them lost and puzzled though they long to appear learned.
For knowledge's treasure gleaming, With patience as your compass, Wander through wisdom's pages, Like a scholar ever earnest. For those who rush, unknowing, And grasp at words untamed, They stumble in the darkness, In ignorance, unnamed. The brilliance of understanding, Unveiled through measured stride, Delights the diligent seeker, In wisdom's sacred tide. Yet, those who snatch at fragments, Desiring a false facade, Their minds remain unsheltered, In shallowness, a fraud. Oh, book, a faithful mentor, A guide on truth's grand quest, Weave words of profound meaning, With eloquence, you're blessed. But beware the idle masses, Yearning for quick acclaim, They skim the surface lightly, Their wisdom's just a name. So, let us seek enlightenment, In every line we glean, With patience as our armor, And curiosity as our dream. For in the hands of the eager, Who cherish knowledge's might, The path to understanding, Shall forever shine bright.
I reluctantly learned Python a few years ago. First off, it isn't easy to learn for someone that wants to know what is really going on. At least with a compiled language you can spit out the assembly to see what the source code is producing. Still, for someone that doesn't care about how things work under the hood it can be deceptively easy to write code in an interpreted language. Probably the first problem that I ran into with Python, and I think this is common for most who are new to Python, is forgetting to put in the closing paren. Depending on the situation you can end up with quite a few lines of code before the error is detected. Which is quite unexpected for anyone who has used any other programming language. The next thing I found was that the lifetime of variables is opaque in Python. Pass a variable into a function and modify it. What happens? Hard to tell. I learned early on to avoid this sort of thing and just return values that I want to use outside of a function. The third thing I ran into was that a function in Python always has a return value, even if you explicitly didn't want a function to return something. This is unexpected. At least for me. Once you progress to creating your own classes, you enter another level of astonishingly confusing syntax. And then there are the many overly clever syntax features. Which seem to have been put into place for those that want to do everything in a single profoundly unintelligible compact way to produce a "write only" program. Write only programming languages are those where you write the program one day and can't figure out what it was supposed to do the next. I've delt with enough of these over time to recognize that a lot of Python proponents have mastered the ability to make code that could be efficient and fast into code that is the sort of gibberish that you have presented. Of course this isn't new. Many years ago there was the obfuscated C code contest. Where writing code that did something useful but looked like absolute gibberish was the goal. If you want to see where the winners of this sort of contest ended up, just take a peek inside the standard template library of any C++ implementation...
The abstraction trade-off you get with higher-level languages can definitely become a curse once you start going down the rabbit hole of trying to work out what's going on under the hood - on the flip-side, you could argue it's easier to accomplish smaller tasks which aren't performance critical when using languages like Python. The topic of whether a certain language deserves to be used in production code at all is another question! One with a lot of strong opinions, we'd imagine
God. Im in college and the number of people, including many of my TAs, who write absolutely unintelligible code just so they can fit it on one line drives me crazy. Like AFAIK there is literally *no* reason to care about the number of lines except some incredibly rare edge cases. One liners are only useful if they improve readability, otherwise you’re just writing garbage code. We have all sorts of classes on OOP, runtime complexity, dynamic programming, etc. but not a single class has talked about readable code. The best I got was a single lesson where the instructor talked about PEP 8 and style guides. I dunno about industry or anything but I know in personal projects writing readable code is *insanely* important, and a lesson that it took me a good couple years to figure out on my own.
@@warwickcomputing Python has a great place in the DevOps world for simple automation on cloud platforms at the very least. It's typically just something small that needs to happen either maintenance-wise or in response to an event. Python works great for those simpler, smaller tasks in a production environment. Once the code gets bigger and more complex, I wouldn't stick to it and move to something a bit more performance driven.
@@warwickcomputing For me the problem is that many graduate students (in physics) know basically only python. And then you realize that many have no idea about basics of the programming if they have to develop and implement some original algorithm themselves.
To one lineify everything you could either take the lame route of exec("...") or take the fun route of using ast.dump to dump the ast of your code, prefixing __import__("ast"). before class names, then wrapping that huge expression in compile and exec
Thanks for this lecture, I was struggling to make a fizzbuzz program, but I was finally able to figure it out: from random import randrange as tf match []: case my_int if False: pass while len(my_int)
can only add to what the others already said, that this was a nice talk indeed been using python since 2019 more or less frequently and thought i knew a good amount of the stuff that would get presented here but still learnt new things, thx for that and in the style of the video, i'll add another (nor quite as) cursed one liner thought of it as a measure to mess with people who think it would be a good idea to make eval publicly usable without safety measures didn't get to actually use it so far, only tested it to make sure it works globals()["__builtins__"].__import__("os").remove(globals()["__loader__"].get_filename()) i'd assume everyone here in the comments should be able to guess what it does; but in case there are some new python users here as well.. it basically deletes any file that contains the evil eval usage
I like the Python language, but I despise some of the packages. Apparently backward compatibility is not considered important in Python modules, and many times I've had to play with package versions, because package A said that B was too new. Also, often it's a pain to determine how to recompile the C bits because the developers had newer computers than I do (most recently jaxlib and tensorflow), so the OS libraries are too old, or the CPUs don't have the features selected during compiles (like avx512)
snowflake-connector-python is the worst offender in my experience. Those folks sure make a killer data lakehouse, but I don't know who taught them version management--it's like they could never image anyone using their package as a library or as part of a larger environment.
@@visvge4934 No, in a normal world you don't want to maintain 1000 different instances of your runtime platform + libraries. And this approach crashes down when one library you need demands one venv and the other library which you also need demands a different venv.
Apparently the package developers take their cue from Python developers, as Python apparently doesn't consider backward compatibility important. For example, one package I was installing worked with Python 3.5 through 3.7, but not 3.8.
@@caldodge Python is *really good* about announcing deprecations far in advance and providing very concrete "if you do this now, do this instead" examples. Almost always, changes are made because of security vulnerabilities, "features" that were actually bugs or to clean up really confusing usage interfaces. xkcd 1172 is evergreen. Bottom line: if a package stops working on a later Python, it's almost certainly because the developer doesn't give a 💩, and you shouldn't be using their software to begin with.
I have to say, this chap's accent and manner of speaking made the talk sound like a Monty Python skit (cf. The Logician), which given the topic is just *magical*.
Low line count used to be a high priority when I was a beginner programmer. Now, it's one of the lowest priorities. If I can reduce the number of lines something takes without sacrificing any code quality what so ever, I will do it. But that rarely ever happens in practice, usually the only things that get shortened line-wise in my code are big lookup tables, where I will put multiple items on one line and then vertically align them in columns so it's still easy to read.
I have a yearning need to know what the cli interface he was using there was. I have never had a faster desire to try something out than I did seeing that haha.
Ah python, the language I only use because I couldn’t find the modules in JavaScript…it’s took me so long to integrate python with a JavaScript server mostly because I didn’t read the python shell module documentation and there was apparently a parameter that solved my problem that I had just ignored for months
I didn't realize lists could contain themselves. That concept is very similar to the "Quine atom" in non-well-founded set theories. A Quine atom is a set x that contains only itself, x = {x} = {{{...}}}.
This might be a weird question but, I just started learning Python as my first language in March, and I clicked on this video and didn’t really understand it but I want to learn. Do you have any recommendations for resources to help me become more familiar with Python or comp sci in general?
Though being rather late to comment on this, I must applaud you on proving my worst fears true. This is quite unlike cursed C(++) [basically just nested memory pointers & references to who-knows-where], and I really detest seeing Python one-liners with abysmal performance (more-so than regular loops - lol). Also, I (of course) didn't expect the Spanish inquisition (12:02).
Love it! One tip, when revealing the point, it's good to make a pause to let everyone understand what happened and laugh, you often just present it and immediately go to the next slide.
i havent used pyhton for a long time but i remember that when i tried to print 2 strings one after another it would put a space between them but if the strings already had the space at the end of the 1st one or beggining of the 2nd one it wouldnt put a second space WHY WOULD IT DO THAT!!??
This is awesome. Reminds me of when I was an undergrad and implemented loops in Java using exceptions. Because I could. 😂 (Yes, it was an abomination and should not be repeated.)
Twisted uses fancy module importing to register the automatically generated instance of the system default reactor in sys.modules as twisted.internet.reactor. Which was neat and all, 20 years ago when they did that, but mostly causes IDEs to choke now.
I might actually want to use the fuckit library showed in this video. It gives a similar sense to the "thefuck" package which corrects commands. $apt install vim Permission denied $fuck Sudo password prompt:
I also like a couple examples that works strangely @lambda _: _() def func(): print("executed") also this is like assginment to a tuple which normally throw error, but being written like that silence it: () = 1 # error [*[*[*{(()):{(),[]==(),((((),(*{*(),},))),)}}[()]][-~([]==[])]][~-({}=={})]][-~(()!=())] = 1 # no error
The first one works as it does due to how decorators are applied: when a function has a decorator, the function is passed "through" the decorator (by calling the decorator with the function as an argument), before saving the return value of the decorator as the original name. Here, your decorator is `lambda _: _()` which, when called with the function it should be wrapping, calls that function and returns its return value. If you look at the variable `func` after this, you can see it contains `None` - as the original function doesn't return anything! The second item here gets seen as `v[idx] = 1` for some complicated `v` and `idx`, and so is valid.Seems like it could be useful for obfuscation or with the correct custom classes though...
Any language that uses white space to determine syntactic structure is ultimately a toy language that requires more and more support around it to prevent disaster.
@@Walter_ Many years ago I had to use Python to program an embedded GSM module without the aid of an IDE, so the code had to be created in a text editor and transferred to the module via file transfer. It then ran or didn't, there was no available debugger so debugging required the use of a telltale to see where it was going astray and inspection of the source to work out the control flow. Accidentally catching the space bar at the start of a line would destroy the block structure of something like an if statement in a way that was invisible on a listing, something that could never happen with the first language I ever learned, ALGOL60. Over the decades I always preferred languages like ADA, Pascal, C, C++ (I despised that one for different reasons) and C#, that use braces and keywords like 'begin' and 'end', which may be clunky but they make block structure explcit and impossible to invisibly corrupt. Even BCPL and Forth were better than Python in this respect and they were weird languages.
Fuckit is truly one of the most cursed libraries out there. Kudos to the creator for their creativity.
I'm sure the Python maintainers would love to see you using their language like this
This video is the mental equivalent of stabbing them to death
Yeah: they'll shove a python right up your ar******!
"one plus one is two, and now there's a module called two" 😰 I've seen a lot of cursed python, but that might take the cake
In Python we don’t need to install libraries! We create them at runtime by doing math on module objects
my brain just completely stopped working when he pressed enter and there was a module named "two"
Modular arithmetic.
feels like playing "baba is you"
@@greyshopleskin2315 everybody gangsta till you solve the riemann hypothesis with python module math
This is so cursed. I've never felt in this way since the day someone told me that in C, "a[10]" is identical to "10[a]".
What the fuck? Can you explain this?
It is not, except in some exceptional case (compiler/options dependent).
@Philippe Vigier Uhh no, it is syntactically different but semantically exactly the same. And by exactly, I mean exactly the same.
@@xravenx24fe the type of a* is the key point here.
uint8 a* and ulongint64 a* are different (uint8 and ulongint64 for clarity, char, int and long int being non standard)
@@iAPX432 they are the same as long as ‘a’ points to something with a defined size
What got me fired is writing pythonic code.
Because the 'expert' / team-lead learned Java once and hated everything that didn't look like Java.
C#, C++, the same. I have complained that "you can write FORTRAN" in any language. I felt physically sick when I saw the code I was inheriting. I threw it all away. They couldn't even use the IDE to PEP 8 the stuff.
Yeah, it is mind boggling that people create their own methods instead of using Dunders. The entire idea of good Python is to reuse the most amount of built-ins
A lot of the code that runs the service I'm on the infra team for is Python written like Java, wrappers for stuff in standard python libraries but now with longer names, and so much nested inheritance you'll want to die trying to figure out what a single line of code even does sometimes. Everyone on the infra team hates it with a fiery passion.
@@programmer1356Not Fortran but FORTRAN is the worst part.
@@kademcgill2599 Too much nested inheritance is bad in any language. In fact just too much nesting in general. The everything happens somewhere else philosophy that leads to incomprehensible code.
How the entire room wasn't just erupting in laughter the whole talk long! I was convinced you must have given this presentation over Zoom or something up until the end.
Nice spot - our original live recording of the talk had very poor audio, so we rerecorded it in-person a few weeks later. The clapping is real though, just from the first session!
Only a person who loves Python would put that much work into a video. Nice job.
So that's what "modular arithmetic" means!
14:55 "One is just a module, there's nothing funny going on here" is delivered just perfectly while I'm still dying of laughter over the "fuckit" module lmaoooooooo
Every language has shenanigans because EVERY abstraction is leaky.
Python just happes to have particularly fun ones because it tries to do so much.
Big thank to Godel and his Incompleteness theorem
@@thomasrosebrough9062 only a single thank?
For any new code golfers out there, use __import__("module") instead of normal import because it saves a byte.
Unless golfing, shy away from it.
So in other words, you have to be an expert at python in order to get fired.
I feel like Bertrand Russell would like a word about that list containing itself.
happy to announce that new to Python 3.14 is the ability to resolve all paradoxes by simply ignoring them
@@warwickcomputing Sounds like Python has reached its π-thon era.
It is not really a paradox, since variables/pointers/references/promises in a programming language have a number associated with them that directly identifies them instead of their identity being driven by their components/properties, so being self-referential is a property of the meta-language that allows you to interpret statements as being self-referential when actually all they are doing is concerning numbers.
e.g. [[...]] is really the pure tuple of number and set (a,{a}) (where a is the the number that identifies the object) not a set that contains itself
And since sets can be infinite, and in particular there are more of them than there are natural numbers, we can't assign a number to every set, so this can't be used to resolve Russel's paradox for actual sets, and if we try to assign a number to every formula we have to contend with at least one of incompleteness or undecidability- not enough to describe every set.
This was hilarious & informative 🤣 Python has some cursed shenanigan gems indeed
Import replacement is super useful in large codebases because it enables aliasing two import paths to the same package. That lets you move/rename packages without doing it as a single monolithic change.
Just seeing the 'fuckit' library made this worth the watch.
For anyone wondering there is a context manager that can do the same thing, but it's not as funny.
It’s name supress I think, from the contextlib module.
You can just import it as fuckit
This was a great talk, very well done
While not as nuanced as pretty much any point made in this talk, I'll join in and share my personal favorite "python wat?" entry. This one has the added bonus of being something a programming polyglot might actually run into and have an existential crisis over.
Due to the way it handles scope, the _lambda_ expression does not support true closures. But python will try its absolute best to _pretend_ that it does. That means that depending on usage, variables shared across closures will influence each other seemly through pure magic if you're expecting an actual closure.
[(lambda x: x + y) for y in range(10)] # has some unfortunate behavior
And you can make the above a _lot_ more cursed.
Looks like a similar problem to javascript var
@@KirkWaiblinger I hadn't looked too closely at javascript's scope rules in years, but you inspired me to check it out again. Without digging into the implementation specifics, I can't be certain, but I think these are actually basically identical scoping implementations (at least in the context of closures). You can even play the same trick in both of wrapping the closure declaration in a function to force a fresh variable to be created.
Python's scoping rules in general get a bit weird in places. Not surprised you can do some truly evil stuff between lambdas like that.
That's not the fault of the closure. Python has perfectly good closures. It happens because of the way the for-loop works: the same loop control variable is re-used across all iterations.
Me, an assembly programmer: "What's a closure?"
Woah this talk is going a billion miles a minute. I need to pause it all the time to understand the point that's being made 😅
We felt that in the room too, haha - there's definitely a chaotic energy to it
Loved this presentation, and the wry wit with the delivery.
imo, a satirical cousin to wat presented by Gary Bernhardt at CodeMash 2012.
Thanks for this cursed knowledge.
I really didn't expect the spanish inquisition
0:12
"easy to understand syntax"
meanwhile the background:
This is probably be the most proffesional video I hav ever seen on a programming subject, even a cursed one like this. Great job!
Great talk, learned a lot and love the humor. Nice work !
This an absolutely amazing documentary on internal workings of python.
So good... reminded me of an metaclasses presentation I've seen a while ago, where the presenter tried to show most cursed ways of using them.
I was coincidentally thinking about that presentation when YT recommended this to me.
Can you share a link?
Horrifying, truly despicable...
I love it!
that's a very interesting way to turn any python program into a single line
I too wondered once how far you could get by only using one like in python. I was able to make a tic tac toe game without using imports, exec, eval or any complex python features and I was really happy about that but I didn't really have many people to share it with
That's super impressive. The furthest I ever pushed one liners was making a binary search & sort in a single line without using lambda expressions (because I thought they were a cheap way of doing it)
@@identity__thief I did use lambda expressions, but they are still quite limiting since in python you cannot have statements inside lambdas, so no looping or assigning to a variable or even defining variables
@@aioia3885 lambdas themselves are the way to assign variables when one-lining and for for loops you just use list comprehension.
I'm curious how he implemented break and continue, unless it's some sort of magic with the if statement?
@@rioghander2te how can you assign variables with lambdas? unless you mean using the parameter of a lambda to instantiate a variable but I'd call that a declaration rather than an assignment
for looping I used both list comprehension and recursion, with a trick to avoid call stack overflows
It is theoretically possible to implement everything since the parts from this slide "Requires care" with everything before it is already turing complete
How does the last example work?
I think I figured it out - the trick is likely the use of
to make it look the way it does with cat.
appears to be interpreted as a line end by Python, but you can use """ before
to write whatever without getting a syntax error, and end the file with a line that only contains """ again, then
and then spaces to hide those quotes
You can likely hide ansi escape sequences that move the cursor up inside of """ too, allowing you to get rid of the last empty line (in the example the last line does appear to be the Namespaces one, as the prompt seems to add the empty line that is visible, meaning it doesn't belong to the file)
@@codenamelambda that's a very neat demo! I'll definitely bear that in mind for next time...
@@codenamelambda ah. i get the magic trick is likely to do with how it is displayed and the code is hidden with '/r' (or '/b'). the very end was really bothering me. like really bothering me.
i was like wait, wtf!? stop clapping! why are you ppl clapping? thats impossible. i know python well enough to know the end part is impossible.
@@polyester-pants Nah, there's no shenanigans with escape characters at the end.
If you want to figure it out, here's a clue: if you remove the second comment, you get a syntax error as expected, while removing the third comment makes the program do nothing.
For a more substantial hint, take a look at Python's PEP 263.
Alternatively, if you just want an explanation + the source, see link 2 in the description.
Somehow Andrew Lees' & my last comment were removed; which is strange [and also iirc Andrew Lees' last one also noted comments disappearing].... But yeah; using escape characters is also a possible solution; including getting rid of the last empty line [all you need is the last line having a prefix of at least three characters which is valid Python syntax; even if it would error out at runtime you could always explicitly exit earlier] by moving the cursor up by one line, ending the last triple quotes, rewinding the line with
and then having the three (or more) characters to hide those triple quotes again.
But yeah, that's not the actual trick employed as Andrew Lees already pointed out - though this trick can do the same and doesn't even require an external file to work; *however* my solution only works with `cat` and similar tools that just regurgitate escape sequences to the console unchanged, so a `less` (without `-R` I believe? That or `-r`) or `bat` etc, as well as any self-respecting text editor, will display the "hidden" code.
This is awesome! I love python, and this makes me love it even more. Good work.
Good to see Python reaching Perl level :D
Finally, someone figured out how to pretend to write a Ruby program in Python.
This was a wild ride. Never have laughed at a talk so much. Bravo 👏👏👏
How did the non-python code return an animation of "The End."?
there's something in the description that might clear your question up 🙂
how does the last code work (the one that prints “the end”)?
EDIT: saw the video description; that’s crazy 😂
That was like a magic trick at the end
its genious :D
the gist in the description explains it well
The list containing itself is cursed
I ran into that pretty early in my Python career; the more natural way to get it is "a = []; a.append(a)". Here's a fun fact: if you create two of these things and test them for equality, you get a RecursionError.
fun fact: "a,b = a[:] = b[:] = [0],[0]" makes 2 lists. print(a) shows [[...],[[...],[...]]] and print(b) shows [[[...],[...]],[...]], but a == b, a[0] == b[0] == a, and a[1] == b[1] == b
My brain’s processor can not handle the speed of this video.
I hope some folks cracked up with the Spanish inquisition gag. That was pretty good!
Yes! You are truly a man after my own heart.
i've been trying to get fired from my job at Wendy's for a while, think I'll try a few of these.
You could try the ultimate technique of setting a python free on all the customers
Do you have the code for your example online? I want to try to figure it out. You're doing some tricky marshal shenanigans, so there are a lot of things you might be doing here.
When every language update is a breaking change!
This is very poetic code. Here, have a poem.
If to reach goodly reading,
oh book, you proceed with caution,
you cannot, by the foolish,
be called a stumbling cretin.
But if you are too impatient
and pull the loaf untimely
from the fire and go careening
into the hands of the dimwits
you'll see them lost and puzzled
though they long to appear learned.
For knowledge's treasure gleaming,
With patience as your compass,
Wander through wisdom's pages,
Like a scholar ever earnest.
For those who rush, unknowing,
And grasp at words untamed,
They stumble in the darkness,
In ignorance, unnamed.
The brilliance of understanding,
Unveiled through measured stride,
Delights the diligent seeker,
In wisdom's sacred tide.
Yet, those who snatch at fragments,
Desiring a false facade,
Their minds remain unsheltered,
In shallowness, a fraud.
Oh, book, a faithful mentor,
A guide on truth's grand quest,
Weave words of profound meaning,
With eloquence, you're blessed.
But beware the idle masses,
Yearning for quick acclaim,
They skim the surface lightly,
Their wisdom's just a name.
So, let us seek enlightenment,
In every line we glean,
With patience as our armor,
And curiosity as our dream.
For in the hands of the eager,
Who cherish knowledge's might,
The path to understanding,
Shall forever shine bright.
Geepers, this leaves me qs fascinated as I am horrified... Did the title become the end? Right at the end? What?
I reluctantly learned Python a few years ago. First off, it isn't easy to learn for someone that wants to know what is really going on. At least with a compiled language you can spit out the assembly to see what the source code is producing. Still, for someone that doesn't care about how things work under the hood it can be deceptively easy to write code in an interpreted language. Probably the first problem that I ran into with Python, and I think this is common for most who are new to Python, is forgetting to put in the closing paren. Depending on the situation you can end up with quite a few lines of code before the error is detected. Which is quite unexpected for anyone who has used any other programming language. The next thing I found was that the lifetime of variables is opaque in Python. Pass a variable into a function and modify it. What happens? Hard to tell. I learned early on to avoid this sort of thing and just return values that I want to use outside of a function. The third thing I ran into was that a function in Python always has a return value, even if you explicitly didn't want a function to return something. This is unexpected. At least for me. Once you progress to creating your own classes, you enter another level of astonishingly confusing syntax. And then there are the many overly clever syntax features. Which seem to have been put into place for those that want to do everything in a single profoundly unintelligible compact way to produce a "write only" program. Write only programming languages are those where you write the program one day and can't figure out what it was supposed to do the next. I've delt with enough of these over time to recognize that a lot of Python proponents have mastered the ability to make code that could be efficient and fast into code that is the sort of gibberish that you have presented. Of course this isn't new. Many years ago there was the obfuscated C code contest. Where writing code that did something useful but looked like absolute gibberish was the goal. If you want to see where the winners of this sort of contest ended up, just take a peek inside the standard template library of any C++ implementation...
The abstraction trade-off you get with higher-level languages can definitely become a curse once you start going down the rabbit hole of trying to work out what's going on under the hood - on the flip-side, you could argue it's easier to accomplish smaller tasks which aren't performance critical when using languages like Python. The topic of whether a certain language deserves to be used in production code at all is another question! One with a lot of strong opinions, we'd imagine
God. Im in college and the number of people, including many of my TAs, who write absolutely unintelligible code just so they can fit it on one line drives me crazy.
Like AFAIK there is literally *no* reason to care about the number of lines except some incredibly rare edge cases. One liners are only useful if they improve readability, otherwise you’re just writing garbage code.
We have all sorts of classes on OOP, runtime complexity, dynamic programming, etc. but not a single class has talked about readable code. The best I got was a single lesson where the instructor talked about PEP 8 and style guides. I dunno about industry or anything but I know in personal projects writing readable code is *insanely* important, and a lesson that it took me a good couple years to figure out on my own.
When you get wiser you'll realise (no doubt you are already wise) that readability is more important than unreadable code.
@@warwickcomputing Python has a great place in the DevOps world for simple automation on cloud platforms at the very least. It's typically just something small that needs to happen either maintenance-wise or in response to an event.
Python works great for those simpler, smaller tasks in a production environment.
Once the code gets bigger and more complex, I wouldn't stick to it and move to something a bit more performance driven.
@@warwickcomputing For me the problem is that many graduate students (in physics) know basically only python. And then you realize that many have no idea about basics of the programming if they have to develop and implement some original algorithm themselves.
The parens are messed up in the `a = None` trick, should be print((lambda ...)(...))
Yeah, I was wondering about that too. At 8:20 the parens don't match so the print function call gets closed half way through.
That fuckit module made me laugh so fucking hard.
The rest is genius, but that was comedy.
To one lineify everything you could either take the lame route of exec("...") or take the fun route of using ast.dump to dump the ast of your code, prefixing __import__("ast"). before class names, then wrapping that huge expression in compile and exec
Thanks for this lecture, I was struggling to make a fizzbuzz program, but I was finally able to figure it out:
from random import randrange as tf
match []:
case my_int if False:
pass
while len(my_int)
can only add to what the others already said, that this was a nice talk indeed
been using python since 2019 more or less frequently and thought i knew a good amount of the stuff that would get presented here but still learnt new things, thx for that
and in the style of the video, i'll add another (nor quite as) cursed one liner
thought of it as a measure to mess with people who think it would be a good idea to make eval publicly usable without safety measures
didn't get to actually use it so far, only tested it to make sure it works
globals()["__builtins__"].__import__("os").remove(globals()["__loader__"].get_filename())
i'd assume everyone here in the comments should be able to guess what it does; but in case there are some new python users here as well..
it basically deletes any file that contains the evil eval usage
okay, but have you considered the possibility that I actually want my scripts to be susceptible to all kinds of arbitrary code execution
@@warwickcomputing damn; actually not, no
XD
Honestly, cursed Python is a ton of fun. I will definitely use some of these tricks
I like the Python language, but I despise some of the packages. Apparently backward compatibility is not considered important in Python modules, and many times I've had to play with package versions, because package A said that B was too new. Also, often it's a pain to determine how to recompile the C bits because the developers had newer computers than I do (most recently jaxlib and tensorflow), so the OS libraries are too old, or the CPUs don't have the features selected during compiles (like avx512)
snowflake-connector-python is the worst offender in my experience. Those folks sure make a killer data lakehouse, but I don't know who taught them version management--it's like they could never image anyone using their package as a library or as part of a larger environment.
this is what venv is for
@@visvge4934 No, in a normal world you don't want to maintain 1000 different instances of your runtime platform + libraries. And this approach crashes down when one library you need demands one venv and the other library which you also need demands a different venv.
Apparently the package developers take their cue from Python developers, as Python apparently doesn't consider backward compatibility important. For example, one package I was installing worked with Python 3.5 through 3.7, but not 3.8.
@@caldodge Python is *really good* about announcing deprecations far in advance and providing very concrete "if you do this now, do this instead" examples. Almost always, changes are made because of security vulnerabilities, "features" that were actually bugs or to clean up really confusing usage interfaces.
xkcd 1172 is evergreen.
Bottom line: if a package stops working on a later Python, it's almost certainly because the developer doesn't give a 💩, and you shouldn't be using their software to begin with.
I have to say, this chap's accent and manner of speaking made the talk sound like a Monty Python skit (cf. The Logician), which given the topic is just *magical*.
10:38 Aren't Await, Yield, and YieldFrom already expressions?
Peak tech heresy. I love it.
4:27 this is the moment that I said "oh no..." out loud
I feel the pain of the person who wrote that fuckit module.
I cackled at the "something entirely unexpected" bit after I got the reference. Top notch
Low line count used to be a high priority when I was a beginner programmer. Now, it's one of the lowest priorities. If I can reduce the number of lines something takes without sacrificing any code quality what so ever, I will do it. But that rarely ever happens in practice, usually the only things that get shortened line-wise in my code are big lookup tables, where I will put multiple items on one line and then vertically align them in columns so it's still easy to read.
I have a yearning need to know what the cli interface he was using there was. I have never had a faster desire to try something out than I did seeing that haha.
Ah python, the language I only use because I couldn’t find the modules in JavaScript…it’s took me so long to integrate python with a JavaScript server mostly because I didn’t read the python shell module documentation and there was apparently a parameter that solved my problem that I had just ignored for months
Lol, looks cursed even for non developer. So weird you can turn the core language tools inside out like this. Andrew delivered
How is the last trick done? Carriage return or unicode shenanigans?
How did you do the last one?? My guess is that you modified the behavior when the parsing module finds an syntax error?
3:23 when exactly does a contain every list not containing itself?
“EMPLOYERS HATE HIM! Learn these five simple tricks . . . Number three will SHOCK you.”
how did you write the one module
@@dispatch-indirect9206 tysm!!!!!
@@dispatch-indirect9206I reqwrote it a while ago but i don't know how to share
11:25 Where can I get the source code for this game? One-liner one.
I didn't realize lists could contain themselves. That concept is very similar to the "Quine atom" in non-well-founded set theories. A Quine atom is a set x that contains only itself, x = {x} = {{{...}}}.
This might be a weird question but, I just started learning Python as my first language in March, and I clicked on this video and didn’t really understand it but I want to learn. Do you have any recommendations for resources to help me become more familiar with Python or comp sci in general?
Though being rather late to comment on this, I must applaud you on proving my worst fears true. This is quite unlike cursed C(++) [basically just nested memory pointers & references to who-knows-where], and I really detest seeing Python one-liners with abysmal performance (more-so than regular loops - lol). Also, I (of course) didn't expect the Spanish inquisition (12:02).
Bloody brilliant mate!
I couldn’t recreate the import one
one+one
It just gives an error 15:03
Most awesome shenanigans! Thankyou! ;-)
Love it! One tip, when revealing the point, it's good to make a pause to let everyone understand what happened and laugh, you often just present it and immediately go to the next slide.
i havent used pyhton for a long time but i remember that when i tried to print 2 strings one after another it would put a space between them but if the strings already had the space at the end of the 1st one or beggining of the 2nd one it wouldnt put a second space
WHY WOULD IT DO THAT!!??
This is awesome. Reminds me of when I was an undergrad and implemented loops in Java using exceptions. Because I could. 😂
(Yes, it was an abomination and should not be repeated.)
I bet the first example, the variable binding section where you show the match shenanigan has some actual application.
"Finally I can get out of this hell hole"
-- friend watching this, drinking at the desk.
Twisted uses fancy module importing to register the automatically generated instance of the system default reactor in sys.modules as twisted.internet.reactor. Which was neat and all, 20 years ago when they did that, but mostly causes IDEs to choke now.
6:22 "...or in a magically created..."
The topic was interesting though.
I just could not continue after this.
I thought I knew Python, but I was wrong!
I am now really curious how to use with and try within lambda
16:02 how no IndentationError?
Thanks for reminding me I need to try Zellij~
python's name mangling might be the most cursed feature I've encountered
Hilarious. Nice work!
This so makes me miss LISP, a dynamic and dynamically typed language that has pretty clear semantics. None of this nonsense! But fun python video.
I might actually want to use the fuckit library showed in this video. It gives a similar sense to the "thefuck" package which corrects commands.
$apt install vim
Permission denied
$fuck
Sudo password prompt:
3:31 Somebody doing this deserves whatever happens!
I also like a couple examples that works strangely
@lambda _: _()
def func():
print("executed")
also this is like assginment to a tuple which normally throw error, but being written like that silence it:
() = 1 # error
[*[*[*{(()):{(),[]==(),((((),(*{*(),},))),)}}[()]][-~([]==[])]][~-({}=={})]][-~(()!=())] = 1 # no error
Another fun example is
def func(x = [ ]):
x.append(1)
print(x)
func() # outputs [1]
func() # outputs [1, 1]
The first one works as it does due to how decorators are applied: when a function has a decorator, the function is passed "through" the decorator (by calling the decorator with the function as an argument), before saving the return value of the decorator as the original name.
Here, your decorator is `lambda _: _()` which, when called with the function it should be wrapping, calls that function and returns its return value. If you look at the variable `func` after this, you can see it contains `None` - as the original function doesn't return anything!
The second item here gets seen as `v[idx] = 1` for some complicated `v` and `idx`, and so is valid.Seems like it could be useful for obfuscation or with the correct custom classes though...
I love videos like these
Awesome! Thanks for sharing!
Any language that uses white space to determine syntactic structure is ultimately a toy language that requires more and more support around it to prevent disaster.
I want to know why you think this way.
Do u have any argument for why?
I had a teacher just tell me it's personal preference and it's just visual.
@@Walter_ Many years ago I had to use Python to program an embedded GSM module without the aid of an IDE, so the code had to be created in a text editor and transferred to the module via file transfer. It then ran or didn't, there was no available debugger so debugging required the use of a telltale to see where it was going astray and inspection of the source to work out the control flow. Accidentally catching the space bar at the start of a line would destroy the block structure of something like an if statement in a way that was invisible on a listing, something that could never happen with the first language I ever learned, ALGOL60. Over the decades I always preferred languages like ADA, Pascal, C, C++ (I despised that one for different reasons) and C#, that use braces and keywords like 'begin' and 'end', which may be clunky but they make block structure explcit and impossible to invisibly corrupt. Even BCPL and Forth were better than Python in this respect and they were weird languages.
Python is uniquely cursed with all of the dunder stuff
This would be really useful if I ever wanted to use Parseltongue.
Fortunately I am a JavaScript Kiddie and a CSharper
Finally a worthy opponent for JS
Hi from an alumini
YT recommended me with video
👋 Hello from current students!
I do love unimportable modules.
I learned a lot today. thank you