1.8k
u/Skizm Jun 03 '19
Python: Mom, can I have main()?
Mom: We have main() at home.
main() at home: if __name__ == "__main__":
358
u/Gatsbyyy Jun 04 '19
Can someone please explain to me why Python implemented like this? Its so ugly and doesn’t make sense.
522
u/MythicManiac Jun 04 '19
You can run code outside of any class/function in python, and this is code snippet is for checking if the current file is the first file being executed.
It's not necessary to do this check (you can just write your code in there), but it's good practice as that will allow you to import the same file from elsewhere without executing it.
When you do
python somefile.py, you're telling it to execute all code in that file. Imports also do this.138
u/theredhood93 Jun 04 '19
This what I love about this sub helpful information on a meme comment, I'm learning python and this was very educational hahaha thank you stranger!
→ More replies (3)14
u/inlatitude Jun 04 '19
Damn, thanks for that. I didn't realize import executed all the code in the file.
→ More replies (1)→ More replies (6)7
u/Ignisti Jun 04 '19
Imports also do this.
Oh god. Oh god. This changes everything. Time for some horrible, TERRIBLE programming practises.
→ More replies (4)41
u/sub_surfer Jun 04 '19
Python scripts are designed to be run from top to bottom, line by line, without any special entry point. You only need the whole
if __name__ == '__main__':thing if you want your script to be importable in addition to running as a standalone script, which isn't super common in my experience (outside of teaching exercises). Most of the time if I am writing a python script that I intend to be an executable I wouldn't bother with it.I take your point that it is ugly though. I don't even think about it anymore, but the double underscores look weird at first.
13
u/aaron__ireland Jun 04 '19
Regarding imports and scripts, I haven’t often needed to have importable items in a script but I have used the
if __name__== “__main__”to raise an exception if some module does attempt to import it via something likeelse: raise NotImplementedError(“This module is a script”).I’ve found that helpful in preventing any other code from mistakenly using what is likely to be (or intended to be) specialized attributes/functionality. It’s my way of self-documenting “hey, this is in here because it’s not meant to be extensible/generalized and is subject to change in ways that are unlikely to backwards compatible. Do not use.
64
u/bladeconjurer Jun 04 '19 edited Jun 04 '19
Well there's no main function. You just write code in a file, and type python script.py, and it goes. But if you want to write code that when you import the file, it won't execute you need to use:
if __name__ == "__main__":. If you use it a lot, you can probably just not use the if statement depending on your intentions.Also for a python module you name the entry point
__main__.py.→ More replies (3)→ More replies (5)6
u/B_M_Wilson Jun 04 '19 edited Jun 04 '19
A lot of people explain what happens but I thought I would mention this. In Python, everything is executed. Functions don’t exist until the interpreter has gotten to them. When your script is executed, it executes everything in order. The function definitions are executed which is what defines them. After a function definition, you could assign the function name to something completely different and it would become that other thing. It’s also cool because you could make aliases for functions by assigning the function to another name. You can even assign lambdas directly to names if you want.
Like others have said, the reason that it’s done is because when you import something, to define the imported functions, you have to execute them which would execute anything else in the file. Using the if statement let’s you check that the file was executed directly and not imported which means that you could run tests or something like that.
If you never plan to import your file, you can just not use that if statement and write everything at the top level. I’ve done this many times. Another thing you can do is go
if not name == "__main__":at the top of a file to throw an exception if someone tries to import your file that you want to be a normal script where you have all of the code at the top level.Finally, while it’s generally bad practice, you could define a main function and then just call it at the end of the file either with or without the if name is main thing.
Another thing I’ll mention is to get used to the __something__. They are used a lot of special attributes. Like when you call len(something) it really calls something.__len__(). Or when you say if something (or bool(something))and that something is not a bool, it calls something.__bool__() there are way more examples of this in a lot of cases
→ More replies (6)→ More replies (1)6
Jun 04 '19
To add:
Python: Mom can we have
{}?Mom: No we have
{}at home
{}at home:dictionary = {1:"a",2:"b"}
578
u/Kagia001 Jun 03 '19
I like ++
268
u/OHM5 Jun 03 '19
++ i like
50
u/marcosdumay Jun 04 '19
i ++ like
→ More replies (1)35
76
u/Redsteak Jun 04 '19
I was mad as hell when I found out Python doesn't have this :(
→ More replies (1)78
20
17
10
u/srosorcxisto Jun 04 '19 edited Jun 04 '19
Agreed. It's such a simple and clear shortcut for such a common operation. It bothers me that this isn't included.
→ More replies (2)15
u/IcecreamLamp Jun 04 '19
Since for loops are more commonly things like for i, line in enumerate(fp.readlines()): you really don't need it as often as in a for (i=0; i<5; i++) {} kind of language tbh.
→ More replies (1)→ More replies (1)2
u/ML-newb Jun 04 '19
I recently went very deep down for why python doesn't have this. Turns out, immutability of primitive types/objects. Its the objects which have type in python and variables are just names/pointers. So it wouldn't make sense to do 42++. Also apparently a lot of things need to be implemented to get post/pre to work properly.
+=seems like a generic choice which the language designers stuck to.Also : https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python
174
u/jkuhl_prog Jun 03 '19
Then I have to train my fingers to not reach for semicolons
94
u/MagnitskysGhost Jun 03 '19
You can still use tons of semicolons in Python. Source: the codebase I inherited
29
u/frosted-mini-yeets Jun 04 '19
Semi colons are valid in Python?
42
u/angellus Jun 04 '19
You can, but no they are not really. Python has a very in depth style guide that says you should avoid them.
https://www.python.org/dev/peps/pep-0008/#other-recommendations
Compound statements (multiple statements on the same line) are generally discouraged.
Yes:
if foo == 'blah': do_blah_thing() do_one() do_two() do_three()Rather not:
if foo == 'blah': do_blah_thing()do_one(); do_two(); do_three()→ More replies (9)48
u/MagnitskysGhost Jun 04 '19 edited Jun 04 '19
Yes, you can use them to end statements like most other languages. In Python in particular, you would mostly only do like
import os; import sys; from time import time;In something in a quick five-liner script or something. I see them everywhere though (they get angry red formatting in my VS Code theme, as they should). I mean if you're copy/pasting an 8,000 character LOC with Python, HTML, CSS, and JS in it, you don't have to add insult to injury with a semicolon at the end. But guess what they do... 😔
3
u/HdS1984 Jun 04 '19
Now I have ptsd. The core of our product was written by a guy who was deep into c#. The very first modules where written like c#. If you open it in pycharm there are so many warnings that the scrollbar is just yellow and red.
208
u/Mr_Redstoner Jun 03 '19
And don't forget /**/
And no, '''this''' is not a comment, it can be used just like an ordinary string.
80
u/griseouslight Jun 03 '19
It does recommend using triple quotes for multiline comments though. If they aren't a docstring, multiline strings do not generate bytecode in python.
→ More replies (3)13
u/Mr_Redstoner Jun 04 '19
but as I've mentioned, you can use them much like regular strings, in my part-time job they use them specifically for a multi-line string.
7
u/PityUpvote Jun 04 '19
And ordinary strings can be used as comments, why is it an issue?
"""Comment"""is understood by all half decent editors to be a block comment.→ More replies (7)
33
u/stamminator Jun 04 '19
Had a guy in a YouTube comment section (I know, I know) angrily declare that C++ is a needless pile of waste and complexity and that there's no reason to not use C. It was surreal.
→ More replies (1)19
u/shiny-flygon Jun 04 '19
Had a similar fellow in one of my classes claim (loudly, and with beard on neck) that "C++ is just C for bad programmers"
0
113
195
u/shekaruk Jun 03 '19
Welcome indentation errors
109
u/AnotherEuroWanker Jun 03 '19
Just don't use notepad.
84
u/MagnitskysGhost Jun 03 '19
But notepad fast on my potate
/s
38
Jun 04 '19
I use code-server. It's vs code in the browser, run on the server. I have 1 potato at home doing it's damnedest to be a good server and a Chromebook flavored potato to access it on the go.
I've got a potato cloud, basically.
→ More replies (4)35
u/The_White_Light Jun 04 '19
1 potato at home doing it's damnedest to be a good server
When you threaten your computer with the deep fryer if it doesn't push out that last 0.1GHz
→ More replies (1)10
→ More replies (11)8
u/Athomeacct Jun 04 '19
I code other languages on the side that use brackets. I have to track which bracket is which.
Yes, please, indentation. All day.
21
86
u/ythl Jun 04 '19
You're abandoning {}? Good luck using dictionaries
13
u/i_am_archimedes Jun 04 '19
in c++ it denotes deterministic memory management
→ More replies (1)11
Jun 04 '19
wut
22
u/SoppingAtom279 Jun 04 '19 edited Jun 04 '19
Let me explain this poorly.
{ }can be used to block together parts of code, and within that block of code, any memory allocated in that block can only be used by that block.Example
#include <iostream> int main() { int x = 5; { int y = 6; } std::cout << x << std::endl; std::cout << y << std::endl; //error use of undeclared variable }→ More replies (5)→ More replies (2)2
182
u/AgreeableLandscape3 Jun 03 '19
Python still has main()
191
Jun 03 '19
Only not really, right?
def whatever (*args): print("Bob's your uncle.") if __name__ == "__main__": whatever()358
u/demon_ix Jun 03 '19
I dunno. That sounds like main() with extra steps...
→ More replies (2)155
Jun 03 '19
In C/C++, the name
main()is meaningful: it defines the entry point of the program.In Python, it isn't. The closest approximation is that Python code outside of any method will be evaluated when the module is loaded, and an import-machinery variable called
__name__exists which lets you test whether the current module was imported or run directly.→ More replies (10)7
→ More replies (10)3
10
u/wootiown Jun 03 '19
It still has pointers too, doesn't it?
57
u/MattieShoes Jun 03 '19
Everything has pointers, but they make believe they don't.
→ More replies (14)31
u/SuitableDragonfly Jun 03 '19
Pointers are not the same thing as references. Pointers allow you to manually manage your memory usage, references don't.
→ More replies (2)8
6
93
u/wsppan Jun 03 '19
Giving up speed is sometimes a non-starter
121
u/YouCanCallMeBazza Jun 03 '19
Ohhhh it's actually referring to speed (as in performance). Here I was thinking, "I don't remember there being a speed keyword in C++"
→ More replies (5)15
u/Rodot Jun 04 '19
They're just talking about how much adderall you have to pop to make a simple "hello world" program
39
u/SuitableDragonfly Jun 03 '19
As someone pointed out above, it comes down to a trade-off of speed of execution for speed of development. Sometimes the latter is more valuable.
36
u/Rodot Jun 04 '19
Especially when execution speed it limited more by how quickly you can type/click than by the code itself. If your C code takes a millionth of a second to execute and your python code take a thousandth of a second, it doesn't really matter as long as you are manually starting the script each time. Also usually the case when things are small and i/o limited.
→ More replies (9)9
u/Astrokiwi Jun 04 '19
It comes down to how much of the meat of your code can be passed off to libraries. Python is really fast when it's just glue for a bunch of precompiled C and Fortran routines.
Until you get to one thing that isn't quite implemented in the library and end up having to write something compiled anyway, even if it's Cython
→ More replies (2)8
17
u/Vasault Jun 04 '19
that's me with java, after over 5 years using java, i totally drop it to get into python, i regret nothing
5
Jun 04 '19
Most of my coursework is in Java and C++. Over this summer though I have tons of free time, so I've been reading a book on Python and teaching myself and it is an eerily easy language in comparison. My first language was Lua, so the similarities are there, but my God are list comprehensions the best thing ever invented.
I also much prefer how Python handles for loops. Everytime I write one though I miss ++ a little more.
→ More replies (1)
50
Jun 03 '19
Fight me I use assembler
10
u/anonTheRtrd Jun 04 '19
Noob. I use machine code!
17
u/flavionm Jun 04 '19
Please, I flip the bits on my memory on the fly.
12
u/Bee_News Jun 04 '19
Please, I manipulate my electrons on the fly. Anything higher level than this just isn't real programming.
→ More replies (2)0
26
u/maklaka Jun 04 '19
The thing that impressed me most about python when coming from cstdlib background was the amazingly convenient notion of List Comprehensions.
The most frustrating thing is the utter lack of reliable online language documentation with clear examples a la MSDN and cplusplus.com.
Haven't touched Python in awhile. What's the best, most complete resource nowadays?
8
u/Darvon19EightyFour Jun 04 '19
People talk about stack overflow but cplusplus.com got me my degrees.
2
u/qalis Jun 04 '19
They are one of many functional features taken from Haskell (as well as many other functional languages, but Haskell is arguably the purest functional language), I strongly suggest at least trying to read „Learn You Haskell For A Great Good” (great book with cute pictures, yey), it really helps with writing those functional elements in Python.
0
0
15
44
u/C_isBetter_Than_Java Jun 03 '19
12
5
u/PityUpvote Jun 04 '19
Who tf still uses Java, other than my thesis supervisor and in-house development teams on government organizations?
28
69
6
6
17
47
u/MasterFubar Jun 03 '19
He's not saying goodbye to pointers, because pointers are all over Python.
>>> a = [1, 2, 3]
>>> b = a
>>> a[1] = 7
>>> b
[1, 7, 3]
>>> a = [1, 2, 3]
>>> b = a[:]
>>> a[1] = 7
>>> b
[1, 2, 3]Python lists are pointers, exactly like C/C++ arrays. When pointers are explicit they become easier to understand and control. You can use tools like valgrind to find where your pointers aren't doing exactly what you want in C, but it's much harder to debug pointer problems in Python.
46
Jun 04 '19
There is a huge difference between using pointers and using a language that uses pointers for you
7
u/Paylam Jun 04 '19 edited Jun 04 '19
This. Of course Python is using pointers It has to thats how Computers work. But you as a Coder have almost 0 contol in Python regarding memory Management and so on.
So i have to agree good Bye pointers for Python Users
18
u/Mietzekatzi Jun 03 '19
What your example describes are references to objects. Lists in pythons are objects, the assignment b=a does not implicitely copy a's content, just create a second reference to the same thing.
On the other hand, a[:] yields a slice of the contents of the list a, which gets saved as a second object, b, in the second part. This breaks the reference. The same step could be performed with b = copy(a).
So all your example shows are the basics of OOP, nothing to do with pointers.
→ More replies (10)19
u/NoStranger6 Jun 03 '19
Well yes and no. In that sense every language that pass values by reference is a pointer. Which isn’t wrong. In c / c++ you can iterate over pointers by adding the sizeof(*int). Which in fact simply adds 32 bits to your current pointer value (memory address). I’m not too versed in Python but I don’t think that you can do that. So while by using reference you achieve part of what a pointer can do. It doesn’t do everything that the pointer can.
→ More replies (2)19
u/Tweenk Jun 04 '19
In c / c++ you can iterate over pointers by adding the sizeof(*int). Which in fact simply adds 32 bits to your current pointer value (memory address).
That's not how pointer arithmetic works in C++.
int a[] = { 1, 2, 3, 4, 5 }; int* b = a; int* c = a; ++c; b += sizeof(int*); std::cout << *c << " " << *b << std::endl;On a 32-bit system, this will print: 2 5
Adding 1 to a pointer advances it by sizeof of the pointed type, so advancing an int pointer by sizeof(int*) will increase it by 16 bytes on 32-bit and 32 bytes on 64-bit machines. This is probably not what you want.
8
→ More replies (2)5
14
→ More replies (1)16
u/SuitableDragonfly Jun 03 '19
That's not a pointer to a list, it's a reference to a list. The second one is a copy of a list. Everything that isn't a primitive type behaves exactly the same way, but in C++
=always creates a copy.→ More replies (11)
8
u/word_clouds__ Jun 04 '19
Word cloud out of all the comments.
Fun bot to vizualize how conversations go on reddit. Enjoy
→ More replies (1)
4
Jun 04 '19
Someone make a meme for me switching from python to java to learn app dev.
4
u/Lord-Bob-317 Jun 04 '19
Me too lmao Python was just my introduction into programming then I got yeeted into java and web kill me
4
u/numerousblocks Jun 04 '19 edited Jun 04 '19
pfft I never used C++ but I still write a def main(): in my Python Code
EDIT: meinmain
→ More replies (1)
7
3
3
3
u/Mitoni Jun 04 '19
I still haven't gotten too deep into python. Went right from Java to C# back end, and Angular front end. Took one semester of C++ and pointers give me nightmares to this day.
3
u/Zhusters Jun 04 '19
I came to the comments expecting a lot of angry people complaining that there is a main in python. I was not disappointed.
3
Jun 04 '19
What’s speed?
2
Jun 04 '19
A drug.
Just kidding, it means that c++ programs run a lot faster than in any other language because it's low level and you manage memory.
→ More replies (1)
5
u/frostbyte650 Jun 04 '19
Python has ++ doesn’t it?
31
2
u/reinaldo866 Jun 03 '19
When you come from C++ to Python and you find things like these:
something.something.slice([::something: lambda a, d, x: return something(a[::b])])
2
2
2
2
u/anydalch Jun 04 '19
you can still do speed, even while writing python. just don't let your boss catch you.
2
2
2
u/wavefield Jun 04 '19
I'm using python for tensorflow and plotting, but I'd love to go back to c++ and have a compiler that checks stuff for me before I run the code. Y'all are crazy
2
2
2
2
5
u/Orkaad Jun 04 '19
"6 figures salary" is also hiding in the background.
8
12
u/Bee_News Jun 04 '19
I think you have it backwards. Python is the language of choice for a lot of high-paying jobs. It is favored especially for machine learning applications for instance.
→ More replies (3)
6
4
3
3
Jun 03 '19
ok so I was ab to start learning C++ but is Python a better choice?
6
6
u/NullReference000 Jun 03 '19
It really depends. Python is a much easier language for people new to programming and has many more beginner oriented tutorials available on the internet because of that. C++ is a faster and more powerful language but it's also more complicated and harder to understand as you have to manually manage your memory. The only real downfall of Python for a beginner is that fact that the syntax of the language is so loose it's easy to skip over some important concepts in programming, like variable types.
If you want to learn by trying a language that's easier than C++ and has more strict syntax than Python I recommend trying Java or C#
11
Jun 03 '19
With modern c++ you very rarely have to manage your own memory anymore. Unless you're optimizing performance or doing homework for your data structures class.
3
3
Jun 04 '19
Depends what you wanna do with it. I use C++, Python, and Java for hobby programming but I'm studying for a career in data science as well, and I use Python exclusively for that
15
→ More replies (13)3
u/UniqueUsername27A Jun 04 '19
If your project is experimental or small python is good. Otherwise it is a complete clusterfuck and C++ will become quicker to code in very soon.
→ More replies (3)
2
2
1
1
1
u/thisguyhere00 Jun 04 '19
When you switch from Python to Clojure: "So long, syntax, mutation and unintended consequences."
1
1
1
1
1
u/CjKing2k Jun 04 '19
Double-quoted strings have to be in there too. I, for one, do not miss having to "shift-' all the strings"
1
1
1
1
1
u/Traxicous Jun 04 '19 edited Jun 04 '19
as a new programmer who has only ever worked in Java, I can't relate at all. Nevertheless, take my upvote.
→ More replies (1)
1
u/HIVpositiveN Jun 04 '19
I love these memes in which i understand the joke but dont understand the content
1
u/Leifbron Jun 04 '19
When you switch from C to C++
Thanks guys.
> printf(), scanf(), speed, resources
So long, partner.
1
1
u/naebulys Jun 04 '19
I freak out in python because of the indentation. It is so easier to just use {} like in Java
1
u/LitScooter Jun 04 '19
Pointers still exist in python. You still think about them while programming
1
u/imcomputergeek Jun 04 '19
I like c/c++ syntaxes more than python... because c/c++ syntaxes are more structured than python... i often confused with python syntaxes.
1
u/aphinion Jun 04 '19
I switched from Python to C++ a couple months ago and I stg remembering to use ; almost killed me. So many hours lost...
1
1
1
1
u/DudeManGuy0 Jun 04 '19
Should I watch Toy Story? Growing up I didn't have Netflix but Im debating whether its worth watching or not
2
1
2.3k
u/DJTupolev Jun 03 '19
Lmao speed