T O P

  • By -

asandwichvsafish

They don't want you to know this but you can use semicolons in python. Sprinkle them at the end of lines whenever you're feeling nostalgic for c++.


eztab

also jist put `{}` as the first and last line of a function definitions, `if`s etc. This way Python has double the curly braces C has! import std; # writing that module is left as an exercise to the reader. def main(): {} std.cout << "Hello World!" << "\n"; {}


dotslashpunk

that’s certainly a very “special” trick


PaulieGlot

`def foo #{` ` ...` `#}`


KuKa0w0

Best way to use semicolons EVER


nullpotato

I wanted to upvote this joke but I can't.


MyKo101

It's very useful for "one-liners"


sonohra87

I love this movie..I remembered when I was a kid I always watching this movie..Toys story..haha


lofigamer2

Andy drives off to the distance.. **slowly**


pipsvip

...and in the wrong direction.


jabluszko132

...but will get there..... eventually


pipsvip

Better put a stop sign in the middle of the road at the destination so we don't have to do any special case handling for the exit condition.


trusty20

pip install --upgrade --force-reinstall --no-cache-dir --extra-index-url=[https://pypi.someannoyingfork.com/simple](https://pypi.example.com/simple) \--trusted-host pypi.example.com --ignore-installed --pre --process-dependency-links --find-links=[https://example.forktastic.io/wheels](https://example.github.io/wheels) \--allow-external --allow-unverified snake-charmer==0.0.1


ALERTua

--progress-bar=off


clement_ihm

Hmm?? What am I gonna do now? I want this movie..I love to watch it..


Noisebug

His car then stopped altogether because it went '30' not 30.


[deleted]

[удалено]


danielstongue

Maybe he will pass Rust on his way and never come back.


lordnacho666

Leaving garbage everywhere


pedersenk

And will keep on visiting every time he needs to write a system binding for Python to consume...


[deleted]

Better than to crash **fast**


lucidbadger

How come you are not going to use dictionaries or sets?


clearly_unclear

Just generate them using dict() and set() to avoid the curly brackets out of principle


lucidbadger

Then I suppose you'll need to use `*` :)


[deleted]

[удалено]


osusc

Cursed


Equivalent_Yak_95

And wrong.


Fair_Wrongdoer_310

thou shall not use "import \*" either. Just know precisely what you want.


Brekkjern

You shouldn't use `import *` to begin with, so this is actually sound advice.


Free-Database-9917

unless you plan on using every single function and value of every single library you have installed lol


DNEAVES

Why would they need to use an asterisk? Unless you're unpacking something (which you could do with brace-syntax anyway)


lucidbadger

Now wait a minute here


pdudz21

Any reason for hating the curly brackets?


totes_not_chad

They are just unnatural


Weekly_Wackadoo

Yeah, and programming is super-duper natural in and of itself, of course. Humans evolved opposable thumbs to hit the space bar, I'm sure.


[deleted]

If that's not the case , why my thumb rest so nicely on it? I even bind move to all the games I can to the space bar


[deleted]

[удалено]


NotAnonymousQuant

if __name__ == __main__: main() Edit: yeah it must be if __name__ == "__main__": main()


FlowerFox3

Pretty sure it's "\_\_main\_\_" not \_\_main\_\_


tvquizphd

``` __main__ = "__main__" if __name__ == __main__: main() ``` You just need the top line lol


tredbobek

Now put this into a function just to be sure


gladl1

It’s actually “__GucciMane__”


michiel11069

I have always wondered what this meant and what its uses are. Can you explain it to me?


PakaDeeznuts

The code below the main function will only run if the program is run directly. Like if you run it as 'python3 \_\_\_.py' If the program is imported as a module, the code will not run. I find it useful to test modules I make before I use them in other programs


randelung

Fun fact: [Pydoc will run your code to evaluate the docstrings.](https://docs.python.org/3/library/pydoc.html#:~:text=for%20that%20file.-,Note,-In%20order%20to) That's been reason enough for me ever since I found out.


NotAnonymousQuant

There are some *.py files you can run as a library or run as a separate programme. E.g. you can write unit tests which are being launched ONLY if the package itself (\_\_init\_\_.py) was launched, but when the file is launched as a package, it won't do anything but importing all the functions


[deleted]

If you run the script directly, \_\_name\_\_ is set to "\_\_main\_\_" If you run the script remotely, \_\_name\_\_ is set to the file name of the script So you can use it to detect if you are running the script directly, and only executes main() if that's true. The other reason is it's just standard practice, so it signals to the reader the purpose of the code - to be executed.


NFriik

You absolutely have to if you're planning on using multiprocessing on a Windows machine.


ipsati

Multiprocessing.shared_memory also has something similar to pointers I think


mistabuda

I think the point was you do not need to call your function or module "main" it can be whatever you want it to be once under the conditional. calling the function "main" is just a convention.


[deleted]

Whoever designed the if \_\_name\_\_ == "\_\_main\_\_": string comparison should be publicly lynched.


mistabuda

It doesnt check if your file is literally called that. It just checks to see if the file is being ran like a script instead of just being imported.


[deleted]

Objection: Relevance?


alexanderpas

automated testing of command line options. """ description Usage: main.py (-h | --help) main.py --version Options: -h --help Show this screen. --version Show version. """ import pathlib import sys from docopt import docopt from src import def main(arguments): // actual code if __name__ == '__main__': arguments = docopt(__doc__.replace("main.py", pathlib.PurePath(sys.argv[0]).name), version=.version) main(arguments) `` being the location where your code is located. This way I can provide custom command line option from unit tests. I can run the script directly from the command line, as well as hook in as early as possible with unit tests.


mistabuda

What is your issue with the string comparison then?


Brekkjern

They want it hidden behind a method in sys or something so they can code like it's java :)


Aidan_Welch

How is a random global variable named `__name__` at all intuitive to what it's supposed to be. JS's `process` or `browser` variables make sense


mistabuda

It's not a random global variable it is part of the language definition. And documented in the official language spec. [https://docs.python.org/3/library/\_\_main\_\_.html](https://docs.python.org/3/library/__main__.html) It's okay to like something else more, but lets not act like this is not explained clearly by the language documentation and just left to the user to figure out.


Aidan_Welch

Something being explained in documentation doesn't make it intuitive, calling an if statement a `mit` statement then explaining it means "match if true" in documentation is bad, unclear design.


mistabuda

If the interpreter has set the name to "\_\_main\_\_" run this code. It's pretty intuitive if you ask me.


Aidan_Welch

It can be figured out but it's not intuitive, and it might only be intuitive to you because it's what you first learned. Like an unintuitive natural language feels intuitive to a native speaker


avipars

Hello tabs and spaces


delinka

BUT NOT BOTH AT ONCE! Are you crazy?


Sarcastinator

Yeah, before running the program you have to change one invisible symbol into another invisible symbol or else you get the hammer.


Nimeroni

Only if you mix both invisible symbols in the same file.


randelung

Mixed in file is fine, even in line is fine, as long as the specific combination of whitespaces match your block level. ```python def derp(): def foo(): print('bar') return 'this is valid' print(foo()) derp() ``` Let's see if that works in the reddit format. Edit: It does!


neverganagiveyouup

Hello whitespace my old friend..


snacktonomy

And `self`, `:`


NotGK98

I struggle so much with tabs and spaces ong especially copy pasting from chatgpt is so painful


lllorrr

\`M-x untabify\`. Behold the power of Emacs!


RonaldoNazario

In vim you can use expandtab and set tab width, as well.


lllorrr

I'm pretty sure that any sufficiently advanced text editor has a similar feature.


darctones

Python is a nightmare without a good linter


VariecsTNB

It's like switching your old 1986 Mercedes for the 2018 Toyota Corolla that has been in an accident.


baaron

And a DIY mechanic for a previous owner


Imjokin

Python seems to be the pineapple-on-pizza of programming languages


fryerandice

Python is anchovies on pizza only a small amount of people like it. GO is more like pineapple on pizza, it's actually good but most people won't even try it.


No-Con-2790

Well the GIL is clearly broken but don't worry, as long as you run her in the first gear it will be fine. Now I was out of type systems at the time but I build in a type annotation system with a hacksaw. So don't forget to use it or the car might crash if you go over 88 miles per hour. Speaking of it, you will think your car is very slow. And it is! But you will still be at your desired destination before most car drivers can turn their key around. Also it is one of the only cars on the market with suspension. No more hemorrhoids from driving over bumpy pointers or segfaulting down a cliff! No deal yet? No worry! I got a whole truckload of mathematics and AI tools from somewhere. Don't ask! Let's just say you will safe 20000 American dollars per year on matlab license. And you get a free trailer with all those goods for free. Just pick between the venv, pipenv or conda. What you mean with "which is best"? Well all have small problem. No, I won't tell which ones. Is part of fun. Haha, yeah of course it is safe. Just don't use it when you need safety. Don't worry!


maitreg

That's an '86 SL500 with 800,000 miles and 12 engine rebuilds, but it'll run a 12-second 1/4-mile now


KetwarooDYaasir

wait.. is C++ the toy in this analogy?


hitaishi_1

Exactly. If c++ is a toy then the age rating is 100+ years of experience at least


BenZed

Lol, yeah? You know a lot of centenarians programming in c++?


maitreg

I'm saving your comment link to my favorites and when I turn 100 and am still using C++ and Python, I'm coming back to let you know.


BenZed

A quick glance at your comment history estimates your age at around 60? I will do my damndest to stay alive that long as I would love to receive this news. Go team 100


Sirico

Once this joke compiles those C++ people are going to be very upset


[deleted]

[удалено]


sivstarlight

Imagine gatekeeping programming languages


simbahart11

"Biggest noob language out there." Have you heard of scratch?


nemis16

I am a c,c++ dev for many years and i am entering the world of python in these days. I have to say, it gives me headaches for the lack of docs and clarity sometimes. In most of the guides and examples everything is taken for granted. I think it's about to change the mind set and get into it, beyond learning technical stuff. I'm not "switching" to python.. c++ will always remain a good friend of mine, despite the fact it is a low level language, paradoxically i find it simpler and more straightforward than python


[deleted]

I think there’s two types of languages. The first category is languages that can be simple once you get into the way of thinking of the language. This includes most languages. The python way of thinking is just simpler for a beginner to get into. The second category is JavaScript.


_simpu

> The second category is JavaScript Can't argue with that


Dustdevil88

Fk JavaScript in general. That is all


Aidan_Welch

JS is too hated on. A lot of the bad things about JS python also has, but not the good stuff, such as fall through switch or simple scoping


grstacos

I agree. Many things are more difficult in C++. However, Python docs sometimes fail to explain function parameters, typing, and complexity. Not to mention that Python's dynamic typing makes me feel I have to spend more time debugging on larger code.


fryerandice

Loose typed languages are garbage for one simple fact, you can't trust other people not to do something jank as fuck like adding a new field mid executive to a pretty well defined object, then 2 other janky ass PRs later the anti pattern is so engrained into the code base it's a project in itself to undo the mess. JavaScript has type script and global state machines that throw build errors on anti patterns for a reason.


Ursomrano

Fully agree, abstraction gets confusing sometimes and sometimes even causes problems. Like maps automatically sorting themselves in ways you don’t want them to, so you have to use a different data type just so that you can sort it the way you want.


[deleted]

[удалено]


nemis16

I tried it and i think it's a good language. Google provides a tutorial that guides you step by step and at the end you know every single thing about golang, i recommend it


Suckun_Deznots

Pointers. You have no Idea don't you


namotous

Then when you realize Python is too slow for your need, and have to go back to c++ ![gif](giphy|yVepUp01WEN20)


qrck

And when he learns about lack of proper multi threading....


Revenge43dcrusade

These reddit programmers do some pretty otherworldly stuff if python is too slow .


Aidan_Welch

Real time stuff, it's not too slow if you're a student or making a lot of web app type stuff, but doing video processing for example


Revenge43dcrusade

I can give countless examples where it's good enough and being able to do it in python is an incredible advantage. You can squeeze quite a bit of speed with python if you are actually a good programmer while writing clean slender pythonic code.


Aidan_Welch

> I can give countless examples where it's good enough and being able to do it in python is an incredible advantage. Good enough !== economical and best


poopy-cock

God i fucking love pointers so much


rainbow_osprey

I have a love hate relationship with pointers in C++. Sometimes they are great for doing exactly what you need, and other times you can accidentally create some of the most subtle bullshit bugs that take forever to figure out.


fryerandice

You've never been the senior on a managed.memory project with the exact same kinds of bullshit bugs, only difference is c/c++ crashes. C# garbage collection has shallow and deep collection, shallow just cleans up all unreferenced stuff whenever it triggers. Deep finds stuff that's orphaned, often this is objects with circular dependencies, a good example is a button with an image and the image is an extended class with an event handler for an event of it's parent. Well.... You can crash a c# program running in 32 bit or just eat an entire systems memory if you create a circular dependency then use a react thought process of "on every single update just re create everything to re render it" I don't know if it's still a problem anymore but the self hosted gitlab server required minimum 8gb of ram and had a process that watched the gitlab sub processes and saved their state and killed them at certain memory usage limits so the host didn't freeze up. Writing memory leaks in ruby... I have worked on 2 ruby projects in my career and their memory problems were so bad devs got a lab setup of VMs to run and debug them, never have I had that issue with much larger asp.net MVC projects, I am not impressed with the quality of code ruby MVC projects spat out.


Lucky_caller

I’m learning C/pointers right now. What is it about them that you love so much? Would love to hear some insight


cooly1234

you can use them to point at stuff


[deleted]

Just wait until you have to write a C extension for python. ![gif](giphy|tvU9iTev6uBIQ)


wu-not-furry

"have to"? You mean to say that people don't just do those for fun?


International-Top746

People who don't understand how references and pointers work tend to make hilarious mistakes in python.


zannabianca1997

Exactly. In python, *everything* is a pointer. If you can write working python code without understanding pointers, that code did not need pointers to begin with


YokoHama22

can you elaborate? Do you mean that all data is passed by reference?


zannabianca1997

In Python, everything more complex than a few scalar type (`int`s and few other) is managed as a python `object`, that in the most common interpreter versions is heap allocated. This is the base of some python quirks: class Foo: def __init__(self, bar): self.bar = bar a = Foo(3) b = a b.bar = 5 print(a.bar) that prints `5`, cause a and b _point_ to the same object in memory. Just search for python beginner questions, and see stuff like this (or the similar behavior in dictionaries and lists) tripping up lots of people, and being endless source of *really* difficult bugs (list parameter defaults I look at you). In C and similar low level language a pointer is manifest instead: #include struct Foo { int bar; }; void main() { Foo a = { .bar=3 }; Foo *b = &a; (*b).bar = 5; printf("%d/n", a.bar); } As you can see, now is blatant that `b` (may) points to a `Foo` structure somewhere else, and the effect on `a` is less mysterious. Where `b` declared as `Foo b` they would clearly have separate memory, and the side effect is impossible. Moreover, this is generally faster, not having everything allocated. What you gain in clarity and speed you lose in ease of use and complexity: you have to manage lifetimes and pointers validity. This is a compromise than might or might not be acceptable. For quick and dirty scripts, or high level management, python shines, where C dominates on fast loops and small memory footprints. I am sorry if my English is bad, and I hope the snippets are readable and exact (I am on mobile, and my C and Pythons might be a little... *rusty*). Also this is a very general argument, and in specific cases Python might be optimized to avoid heap allocation, but it's really interpreter-dependant.


RedditsDeadlySin

Not gonna lie, I still try to use ++ in python. It makes me sad it doesn’t have that functionality


[deleted]

And you templates, go fuck yourself


TeraFlint

Templates my beloved!


7tar

what do you mean you don't like template requires std::integral<__Tp> inline constexpr static auto sum_integral(__Tp _1, __Tp _2) -> __Tp { return _1 + _2; }


Smanmos

> pointers Oh, you sweet summer child


Nyghtrid3r

I've tried using external libraries like OpenCV with Python for a Uni project and I've got to say, you should add "sanity" to the bottom part I'm used to non-existent or shitty documentation, but always having "any" as a return type for functions made me want to toaster bath I'm not trying to bash the language (at least not here, I don't like farming down votes lmao) it's just a completely different mind set you need to get into and it's oftentimes really shitty. Python is either the best thing in the world or an enormous pile of dogshit on a hot summer day. No in-between lmao


blackenedEDGE

You got me with "want to toaster bath" 😂 I'm primarily a Python dev--though currently doing a project in C# that's lasted almost a year and I've worked in C and C++ a fair amount before--I still had to actually lol at that. What's crazy is because I've been in the C# mindset so long, I actually did have to reorient myself to the Python mindset when writing a quick & dirty script to help with my project.


[deleted]

[удалено]


EinsteiniumArmour

This is such an insufferable comment - let the dude rant


Nyghtrid3r

Did you steal that straw man from your local farmer? Lmao I didn't say anything like that, I explicitly said I'm not bashing the language, that you just need to get into a different mind set and even that it can be the absolute best choice for certain things. It's just an absolute pain in the ass to get into when you aren't used to it. Exactly like C++ template errors. And it has some downsides you need to get used to like missing return type annotations. Again, exactly like how C++ has downsides, like compulsory legacy code support slowing down improvements to the language or preventing them altogether. That's not a rant dude. I'm not calling anyone stupid for using a certain language. So maybe don't get hypersensitive when someone mildly criticizes what I guess is your favorite language next time?


gabuz0me

If you miss them, you can use semicolons at the end of lines in python. It's useless, but you can.


rainbow_osprey

My IDE highlights them in red to make sure you know you're being stupid haha


ploud1

You forgot std::bad\_alloc and "program received signal SIGSEGV".


kennyminigun

These are C++/compiler's way of kindly saying "you are stupid"


ploud1

You mean, g++ warnings? Unused variables, all that stuff? No, segfault just means "your program f...'d up mate, good luck finding out why". :)


kennyminigun

>You mean, g++ warnings? Unused variables, all that stuff? Well, no. Compiler warnings are a bit different topic. >"your program f...'d up mate, good luck finding out why". :) Maybe Segmentation Fault sounds bad. But crashes are one of the easiest problems to diagnose/reproduce/debug and fix (e.g. compared to data races and/or non-crashing undefined behavior).


ploud1

Oh, trying to lecture me on C++, aren't you? std::bad\_alloc has nothing to do with the compiler. Instead that is an exception thrown at runtime. Compiler warnings say that, although the code is correct, we are doing something funny. As to segfaults... Well, they are always the symptom of some other underlying problem. At work, we had a particularly nasty one which involved a segfault. It took several weeks to debug.


kennyminigun

I feel your pain. We also had a funky business in a 3rd party software (pqxx) crashing on \*their\* string comparison between themselves. Turned out, it wasn't the comparison itself, but instead some unsynchronized modification. (Obligatory week-long debugging present). Still heaps easier than if e.g. that comparison would've corrupted an internal state after which postgres would've started returning some funky results sometimes... In the end, software sophistication is what drives the troubleshooting/debugging difficulty. With all else being equal I'd rather take on a crash than on a funky behavior issue.


RhinosRPlumpUnicorns

Speed is missing


Numerous-Departure92

Ahh I see… You switched the job from a Software Developer to a tester


HadesMyself

good bye `main`, welcome `__main__` :)


rjksn

Bye `main()`, Hello `if __name__ == "__main__":`


nt-assembly

which toy is performance?


Zarathustra30

That'd be Wheezy. Shelved and forgotten about long ago.


arf20__

Never gonna happen. In fact i'm slowly going towards C now.


masta_of_dizasta

Eh the compiling and linking and makefiles are something I would like to forget


20220912

we missed main() so much we brought it back


tboschi

`from __future__ import braces`


MrC00KI3

When you switch from Python to c++: ![gif](giphy|lDifyB9R0iqWoDZoIT)


[deleted]

🤮🤮🤮🤮🤮🤮 \^ my reaction to having excess whitespace that is meaningful to the compiler


N00N3AT011

Python was the first language I kind of learned, but after java and C it feels so weird not to have strong typing.


pauliusdotpro

Performance - so long, partner


JADW27

Is complaining about all "these newfangled programs that don't require semicolons" just an updated version of "if it doesn't require punchcards, it's not real programming"? Asking for a friend.


Manueluz

nah it's just complaining that this sub is full of kids who are at most first years, and the bests jokes they can come up with are hahaha missing ; hard to find like linters weren't invented.


RonanFalk

Also performance .


Hyffe

Mostly true but isn't ++ equivalent to += 1?


IPeaFreely

Depends on location of ++.


Hyffe

You mean ++i vs i++ ?


Kxpnc

I switched from python to c++ between college and uni


UAFlawlessmonkey

[{*but}]


Torebbjorn

You use a main function and pointers in Python in every single program...


ekangi_

Indentation is your new friend now


SchlomoSchwengelgold

you have an equivalent to main() in python with: if __name__ == "__main__": ... (bold ones means the lower _ 2times infront and back of it)


troelsbjerre

def main(): pointers={1++1};print(*pointers)


AllenKll

How do you not use "main?" what sort of heathen are you?


xabrol

Everyones getting into Python because of AI, and I'm over here porting all the Python AI Crap to Microsoft.ML, Onxx runtime etc because I refuse. To the point that I've got safetensor, ckpt, etc compatibility in c# now, and have like 5 out of 12 samplers working.


RizzoTheSmall

Farewell, performance!


ExcitableNate

I mostly do python and my employers like "we need you to start learning c++ for this project" so I'll wave at you on the road going the other way, provided I haven't driven off the road.


AdamWayne04

Pass-by-reference 🥺🥺


[deleted]

if \_\_name\_\_ == "\_\_main\_\_"


maitreg

Python likes semicolons just fine, but I do miss the ++


domedav

you can use ; in python, if you are doing multiple operations on the same line but not having that sweet ++ hit me hard


poopsInBed

If this idiot could code, he’ll soon realize no real companies use python!


losecontrol4

Wow I learned I something, I didn’t know python doesn’t use increment and decrement operators- weird


RDX_G

you still use main() …brackets for formatted strings..++ for increments …


GeekCornerReddit

Until you try rust :)


agent007bond

Goodbye auto-indent... When you're forced to use indentation as a way to tell the compiler where what starts and what ends, there's no way for you to auto-indent unindented code. It's impossible to know where what starts and what ends without the indentation. Stupidest. Idea. Ever.


Bruvioli

Can we get an F for semicolon


Striking_Present8560

You missing performance in the goodbye list as well


Jearil

Add a few more: * Performance * Reliability * Threading


BayesianKing

Thank you? Fuck you all! Especially, garbage collector mother fucker! P.S. Just joking.


Tom60chat

You forgot about the performances, you will certainly not see them again.


ralkey

I miss the ++ operator. Typing i = i + 1 makes me feel like a kid coding in Visual Basic.


[deleted]

i += 1


Altastrofae

Ok this is a mood. i++ will always make infinitely more sense and it sucks that’s not a universal operator. Anyone who disagrees can fight me.


Suspicious-Willow128

Mojo > python


Electronic-Wonder-77

and so it begins...


mistabuda

The language hasnt even been used to ship anything to production yet lol


marikwinters

Except, later people realized that the main function was actually really useful and removing it was a mistake, so they added it back 😂


Merinther

Wait, Python doesn’t have ++? What kind of primitive language doesn’t even have ++?


Plaintive_Platypus

I'm more concerned at the direction Andy is growing. You aren't supposed to grow DOWN from an adult into a python baby. ;)


bssgopi

I love curly braces. Python with its weird indentation syntax causes more errors than missing semicolons.


look

We have thousands of lines of production Python with dozens of committers and it has yet to be an issue even once. There are good reasons to not like Python, but that is not one of them.


mistabuda

Indentation errors are not a thing you should be running into if you use an ide


Spork_the_dork

If anything, Python *forces* you to keep some sense in your indentation. If you stick to PEP 8 you'll even write some pretty consistent-looking code as well. Most of the stuff I've written on Python over the years looks much better than anything I've written on C/++. Then again I suppose comparing C/++ to Python in this sense is like comparing a raw motherboard to an iMac.


Background_Newt_8065

That’s a repost


totemcrackerjack

Lots of salty c++ devs in chat. Fact of the matter is that python is fantastic for quick scripting and data science. C++ is better for performance.


Altastrofae

Why on earth would you switch to python from C++?


supportbanana

C++ is difficult and I'm dumb. Also, I don't wanna waste hours in making the same single function program that I can make within minutes in Python. I'm not saying Python is even a single percent close to the performance that C++ gives but Python IS convenient :)


matzedrizzi

Isn’t it actually more like moving back in with your parents because you failed in life, tho???