If __name__ == '__main__':

>if __name__ == '__main__':

Other urls found in this thread:

python.org/dev/peps/pep-0315/
python.org/dev/peps/pep-3103/
stackoverflow.com/questions/37325667/does-es6-module-importing-runs-the-code-inside-the-file
twitter.com/AnonBabble

And what's your solution then faggot?

it just werks

That's a nice solution, better than developing more bloat just to check if the script is running as a module or not.

>public static void main(String[] nignogs)

python isn't perfect but it sure is just werks in all the right places

Uhhhhh literally every other language has a sane main function

>not double quotes
Fucking plebs.

> Inb4 indentation flamewar

3 spaces are objectively the best

So it's the same thing...

>literally every other language
Literally every "scripting" language works like Python does.
Ruby, PHP, Julia, JavaScript, Lua, Tcl all execute the entire module when you import it so you need some kind of a guard.

you could just write all the code in an unindented block if you wanted

Other languages don't require comparing two ___magic___ __variables__ for the most basic function

>other languages require you to create a magic function for the most basic function

>int main
>__name__ == '__main__'
Oh golly gee i wonder which one is more arbitrary

The one that requires you to specify a return type for a function that does not need one.
Plus you can use the __name__ variable to also execute other functions if the module is loaded by another, rather than as the main module.

char** argv

import sys

def main(argv):
# do shit here
pass

if __name__ == "__main__":
main(sys.argv)

>char** argv
Almost right.

Shitty arguments, they could have just made it so that def main is called by default

What, when your module is imported? Why!?

>his favorite language doesn't have $_SUPERGLOBALS

I think it is interpreter state more than a global variable.

When you write a big piece of software that's broken up into several modules, it makes sense to give each module a main function that lets you test this module's functionality without needing the entire program's source. You can leave that function in each module's source for further testing down the line without adversely affecting performance, precisely because it isn't executed whenever the module is imported by another module.

What said.
Being able to write a main function in each module is a nifty feature which provides you with a ready made place to write your tests which you know would never run in the actual program.
dunder words also make more sense for OO. They provide a uniform interface if you want your objects to be used by other functions (__len__ makes your object work with len(), same for comparison and hashing functions).
It's like you insist on writing ugly code.

And I forgot to mention logging. When you use several modules in your program it really helps knowing which module a log message came from
get a (you)

Then it isn't run

Wow you have described a main function, most languages don't require magic comparison for that

You too are literally describing a main function
>it's like you insist on writing ugly code
The default is a main function *without* comparing seemingly arbitrary values

OK.

> magic comparison
You realise the entry point for a binary is just convention, right? Scarcely the same as this. If you wanted to make it a function instead of a flag it would be __main__ (to avoid collision with usr defined names) and you would still complain. You are clearly someone with a very inflexible mind and should refrain from stepping outside of your comfort zone.

braindead pythonfags

Java has this exact functionality without the magic comparisons.
Pic related is you using a language that sucks so much even fucking JAVA is saner.

>Java
Shoo, off to your designated shitting street, Pajeet.

>ITT lusers complain about language features they don't understand

Avoiding user collision with a main function, do you know how off sounds?

It's a main function ffs, the most basic thing, users can avoid calling a function that is not a main function "main".

And yet Python manages to be even worse.

>i-it's 2deep4u

So you would rather have the interpreter check for a function with a specific reserved name and execute it if some condition is met, rather than... checking if some condition is met and then executing a function of your own choosing?

Also checking __name__ allows you to call different functions (that might not necessarily be called main), depending on the context.

It actually is. You're just too uneducated to realize a main function is not really any less "magic" than a special value in a variable.

Python's approach is actually simpler and more orthogonal, using only simple constructs like variables, blocks and if. The only magic is how the value "__main__" ends up in the variable.

>more orthogonal

How orthogonal does it get?

holy shit I had no idea python was this retarded, LOL!

>Also checking __name__ allows you to call different functions (that might not necessarily be called main), depending on the context.

This. I feel like there should be a more straightforward way to compare __name__ (because it's quite ugly indeed) but still, the concept itself is useful and intelligent. Especially because Python is so heavily module-oriented.
Still,

int main(int argc, char* argv[]) { return 0; }

Is not very beautiful/easy to remember either.

>char* argv[]
absolutely disgusting

>a more straightforward way to compare
How more straightforward than a single if statement does it get?

>(C code)
>Is not very beautiful
true
>/easy to remember either
It actually is, if you take a second to think about how it's put together. All the pertinent information is there: return type, function name, args (number of args, list of args), function body.

>ugly

Yeah Python suffers heavily with that problem when it comes to its stupid __variables__. They say it's by design, to make using those "internal" variables feel wrong, but I think it was a stupid decision. Nobody can change it now though

>It actually is. You're just too uneducated to realize a main function is not really any less "magic" than a special value in a variable.
shit assumption, shit strawman
Also, special values in variables are way more magic than a function name that's consistent across languages descended from C.

>Python's approach is actually simpler and more orthogonal
"Simpler" as in "you now have to do more shit for no benefit whatsoever"? That's a weird definition of simpler.

>using only simple constructs like variables, blocks and if
But again, why should this misfeature be included in the first place?

>The only magic is how the value "__main__" ends up in the variable.
So it's not magic but it is magic. Really activates my almonds.

>way more magic

Not really. Main functions are mandatory. Compile an executable file without one, your compiler errors out. Python is a lot more malleable, everything is executed.

>more shit

It's just a comparison. Simpler and easier to understand than a function definition.

>why

Because in Python and nearly every dynamic language, entire files are always executed when they're loaded, not just some random "main" entry point in the program.

>not magic but is magic

Thr only magic here is the runtime letting you test for the case where a file is executed directly rather than being loaded from another module.

>How more straightforward than a single if statement does it get?

I don't know - Just encapsulate context-Information somehow?
Something along the lines of

context.isMain()

Just doesn't look as hacky and you don't have to deal with internal variables. Still, you could implement something like

context.name == '__main__'

Which would be equivalent to the way it is now.

So you're proposing defining a class so that each function is an object of said class, which defines a method isMain, which polls an attribute (an internal variable) if that object, and then returns a boolean value. You're right, that's way more efficient and less hacky than just accessing a variable that was intended to be accessed in precisely this way.

#
# Internally
#
class context:
main = None

#
# User-Defined
#
def someFunction():
return "Hello World"

def myMain():
print("Main Function of User-Defined Program...{}".format(someFunction()))

context.main = myMain()


#
# Internally
#
if context.main: context.main()


Better example

Just POO my shit up.

>defining a class so that each function is an object of said class

What the fuck are you even talking about?
Im just proposing implementing some kind of wrapper to avoid having to type out some unelegant statement each time I want to write some script that can also be imported by other modules.

If you want to write your program as a small utility or as a script, it does need a return type.

But I guess Python developers never write small programs...

No it doesn't. You never see that shit in Java, C#, or other BIG PROJECT languages.

You know why?
Because while you could do that, it would be FUCKING RETARDED. We have unit testing now. We've had that shit since the Xtreme Programming revolution in 2003. How the flying fuck are Python devs this fucking stupid? How do you get jobs?

> Defending __len__() bullshit
Oh so it works with length?
You know what would also work?
Basic OOP, where you offer length as a method. And as a normal method, not a magic Do Not Use method.

Why are Python programmers so brain damaged? Do Guido deprive you of oxygen until you're dumb as bricks or something?

It's also completely magic that we usually write say,
number = 1 + 3
and expect it to be 4. Why does + sum and not multiply? Why is it suddenly infix? This is completely arbitrary and just an old convention... Just like, you know... main functions/methods.

>Basic OOP, where you offer length as a method. And as a normal method, not a magic Do Not Use method.

This is so that you can implement __len__() for datastructures for which it makes sense. After that you can transparently call len() on objects and obtain the length, independently from someone implementing functions with arbitrary names such as "int getLength()", "int len()" or "int length()". This is why you can call len() on so many different datatypes in python.

Maybe I'm retareded here, but when would length(foo) be able to do something foo.len() would not?

Why would you want to prefer the first? Some example please?

class customDatastructure:
def __len__(self):
return 3

instance = customDatastructure()
print(len(instance))


Again, you can implement a function that returns the length without coming up with a name yourself. It's just there already, just fill it with code. Everybody knows how to obtain the length, independently from you choosing to implement "length()", "len()" or "getLength()". Just streamlining basic operations on datastructures.

Because it's defined to sum and not multiply. Simple as that.

Mathematical functions in these languages are probably handled at the syntatic and semantic level. There's special syntax that lets you say say x + y * z, and symbols like + and * are directly and rigidly mapped to interpreter functions like add and multiply, or even add and mul instructions of an intermediary representation instruction set.

Contrast a language like Ruby, where x + y is actually sugar for x.+(y), a fully customizable method call you can redefine, or Lisp where you can simply redefine + if you want

In Python you can also override binary operators:

class customDatastructure:
def __add__(self, other):
return [x*x for x in range(5)]

instanceA = customDatastructure()
instanceB = customDatastructure()

print(instanceA + instanceB)

as someone who is recently started to learn python, started off in C and fairly proficient at it, I do not understand why these things don't exist:
> constant variables
> do while
> switch case

and a few others I can't name, what is the idea behind this?
other than that my only complain is that you compile to either bytecode or just give away the sources, either way your source code is out there in the open, even with an obfuscator.

>other than that my only complain is that you compile to either bytecode or just give away the sources, either way your source code is out there in the open, even with an obfuscator.

I wonder if he ever thought how you are going to make a living when you don't get paid for your work?

>> constant variables
:(

>> switch case
dude dicts lmao

If you work for a company, the company owns the source-code anyways. Same if you are a contractor that develops Software.

Because Guido van Rossum is a fascist and an terrible programmer (not trolling). Just go and read the python mailing list if you don't believe me.

It still requires special syntax though. In that case it just maps + to some arbitrarily named __add__ method, and maps integer's __add__ to the internal adder function. You also get stuff like the operator module so you can pass them to functions.

More powerful languages turn + into just yet another valid indentifier for a function or variable. Ruby lets you create the symbol :+ easily, the only special syntax is the one that turns x + y into x.+(y). Lisp can do (map + numbers) instead of relying on workarounds like operator.plus.

So it's more like "+" is a function that get passed on through currying?
It's been a while since I used functional programming.

>switch case

Hahaha I laughed pretty hard when some dpt faggot posted python's "switch"

result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}[value](x)

>constant variables
Makes no sense.
>do while
python.org/dev/peps/pep-0315/
>switch case
python.org/dev/peps/pep-3103/

In Python + is not really a function, it's a syntactic element that disappears at runtime. The real function is _add__.

In Ruby and Lisp and (probably others too) you can actually define a + function or method.

class Kek

attr :num

def initialize(num)
@num = num.to_i
end

def +(kek)
self.class.new self.num + kek.num
end
end

In Lisp

(define + -); happy debugging fuckers

>a fascist
Nani?

It's literally two fucking lines you lazy piece of shit. Just write a bash script that generates an empty template and be done with it.

You realize of course, that there is zero difference between calling length(foo) and foo.length() right?
You're just trolling me here, right? This isn't what you actually think, right?

How do you not see the point? The + operator is just as magic as the main function is. If you're going to pretend that main is bad and magic, you must also agree that so are the arithmetic operators. Your arbitrary line is just that: Arbitrary.

(You) see I want to say something insulting back but I can totally see myself in the situation in your picture.

It would make sense to not have the user type out that check every time, but even if he doesn't, wouldn't you still need to check for it behind the scene?
How does Java handle it? Could it be different for compiled and interpreted languages?

I think you are misunderstanding. Too lazy to type it out again, nobody cares anyway.

I like python, but it's lambda syntax is rather limited, although you can achieve quite a bit with comprehensions.

No, it would be the same if it was interpreted.

Java programs start by loading a class with a main method.

From that main method, the other stuff that is referenced gets loaded in. Since classes only contain definitions, nothing gets run. (Except static{} blocks who get run when you load the class, but that has no bearing on this argument.)

If you wanted to have a separate main method that tested a specific class, you'd point java to the class, and it would load the class and run the main method.

>The + operator is just as magic as the main function is.

My post was about how it didn't have to be "magic". Many languages solve the "+ is a special function" problem by allowing it to be a valid symbol. Therefore, it exists within the realm of the language itself, not some "magic" construct outside of the language.

Main functions are magic, but they don't have to be. Python leveraged existing linguistic structures to reduce the amount of "magic" it has to perform in order to let you execute a module.

> If you're going to pretend that main is bad and magic

I don't have to pretend kiddo. Main functions are a linguistic limitation of lesser languages. Python programs are executed as they are read by the implementation. There is no main function. Everything is executed. You can just type your "main" code at the end of the file and it will run. It doesn't even require a function.

This entire __name__ == "__main__" thing exists so that you can execute a module, a library, as if it was an application. Normally, a module is just function definitions, but they can also contain code. However, it'd suck if your module started doing I/O and printing to terminal when some programmer merely imported it, so they gave you a really simple and mostly non-magical mechanism to detect whether someone is importing a module or doing python module.py.

Put that in your C pipe and smoke it. Call me when you can execute a DLL as if it was an EXE

One of the many reasons I love Python. I just wish it was faster. But oh well, simplicity also has its downsides apparently.

>So you would rather have the interpreter check for a function with a specific reserved name and execute it if some condition is met, rather than... checking if some condition is met and then executing a function of your own choosing?
For the most basic function of any program? Yes of course ffs it's a main function fuck, don't force everyone to write the same exact line awkward logic, a function is much more fit for this purpose

>Also checking __name__ allows you to call different functions (that might not necessarily be called main), depending on the context.
Keep that for the 1% of the cases in which it's not a main function

You can dllimport an EXE.

So? An EXE can have symbols too,

In "scripting languages" every script runs as main, so to say.

I do agree that python's syntax is not the most beautful one out there, but the mechanism works.

In Ruby you would simply check if the current filename is identical to current main (it's a somehow mechanism, but not identical !):

if __FILE__ == $0

I like it except there is no default

Why is that stuff even important? Even if you dislike it it's just a minor inconvenience. Holy shit I wonder when people on Sup Forums discuss about non-trivial shit.
People like you make me think that 90% of Sup Forums are either in high school or in the first semester of college.

public static void main(String[] args)
Oh yep much more intuitive

>that there is zero difference between calling length(foo) and foo.length()
The first is a generic function and the second is a method. Are you retarded?

map(len, ['foo', [1, 2, 3]])
map(str.length, ['foo', [1, 2, 3]]) # does not work, like your brain

>Holy shit I wonder when people on Sup Forums discuss about non-trivial shit.

It's like I said in people are simply too stupid to understand why things were made the way they were. People who don't understand anything will just shitpost about them with other like-minded idiots. It doesn't help that programming language design is the domain of the 0.01% programmer. Common folk is simply too ignorant to even begin to understand how Python even works or what a main function really is.

That's because Python can't decide whether it's an object-oriented or a function-oriented programming language.

Ruby has no free functions, only methods bound to objects. However it actually has built-in functionality to make your second case not just possible but easy:

['foo', [1, 2, 3]].map &:length # [3, 3]

The & is syntax for passing a value as a block. In this case, the symbol :length is being passed as a block. So & calls to_proc on the :length symbol, which returns a proc that sends :length to its argument. So what ultimately gets passed as a block to map is proc { |element| element.length }, virtually identical to the len function.

So it essentially generates the "len" function on-the-fly in order to protect the non-understanding luser from seeing the confusing dichotomy between "generic" functions and methods as you have in Python.

for a default you would do:
result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}.get(value, lambda x: x / 2)(x)

>try nested lambdas

python is a hacked together language and it shows. it can't even handle indentation properly. but as shitty as it is it gets the job done so i guess it serves a purpose.

/thread

>JavaScript
Fuck off, no it doesn't.
You need to invoke the function or call it from the main branch of your JS.

Self invoking, runs the instant it is parsed
( function optionalName(){
// code
}())

Anything written in the top level will be executed when the module is imported
stackoverflow.com/questions/37325667/does-es6-module-importing-runs-the-code-inside-the-file

Oh dear christ what fucking idiot thought this was a good idea?

Here I was thinking ES6 was generally going the right direction.

As already mentioned in pretty much every non-compiled language works like that and nobody complained because it's a non-issue.
Having code that executes on import allows you to various kinds of dynamic setup.

It is a GREAT idea you dumb cunt