[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y ] [Search | Free Show | Home]

>if __name__ == '__main__':

This is a blue board which means that it's for everybody (Safe For Work content only). If you see any adult content, please report it.

Thread replies: 96
Thread images: 6

File: opengraph-icon-200x200.png (8KB, 200x200px) Image search: [Google]
opengraph-icon-200x200.png
8KB, 200x200px
>if __name__ == '__main__':
>>
And what's your solution then faggot?
>>
>>61741232
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.
>>
python isn't perfect but it sure is just werks in all the right places
>>
>>61741788
>>61741692
>>61741268
Uhhhhh literally every other language has a sane main function
>>
>not double quotes
Fucking plebs.
>>
>>61741831
> Inb4 indentation flamewar
>>
>>61741847
3 spaces are objectively the best
>>
>>61741796
So it's the same thing...
>>
>>61741796
>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.
>>
>>61741232

you could just write all the code in an unindented block if you wanted
>>
>>61741875
>>61741928
Other languages don't require comparing two ___magic___ __variables__ for the most basic function
>>
>>61741965
>other languages require you to create a magic function for the most basic function
>>
>>61741971
>int main
>__name__ == '__main__'
Oh golly gee i wonder which one is more arbitrary
>>
>>61742358
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
>>
>>61742413
import sys

def main(argv):
# do shit here
pass

if __name__ == "__main__":
main(sys.argv)
>>
>>61742413
>char** argv
Almost right.
>>
>>61742378
Shitty arguments, they could have just made it so that def main is called by default
>>
>>61742868
What, when your module is imported? Why!?
>>
>his favorite language doesn't have $_SUPERGLOBALS
>>
>>61743019
I think it is interpreter state more than a global variable.
>>
>>61742868
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.
>>
>>61742868
What >>61742997 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.
>>
>>61742868
>>61743123
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
>>61743107
get a (you)
>>
>>61742997
Then it isn't run

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

>>61743123
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
>>
>>61743342
OK.
>>
>>61743342
> 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.
>>
File: 1463544959785.jpg (57KB, 640x457px) Image search: [Google]
1463544959785.jpg
57KB, 640x457px
>>61743107
>>61743123
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.
>>
>>61743489
>Java
Shoo, off to your designated shitting street, Pajeet.
>>
>ITT lusers complain about language features they don't understand
>>
>>61743462
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".
>>
File: 1483910852184.jpg (15KB, 183x184px) Image search: [Google]
1483910852184.jpg
15KB, 183x184px
>>61743505
And yet Python manages to be even worse.

>>61743520
>i-it's 2deep4u
>>
>>61743538
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.
>>
>>61743557
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.
>>
>>61743634
>more orthogonal

How orthogonal does it get?
>>
holy shit I had no idea python was this retarded, LOL!
>>
>>61743574
>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.
>>
>>61743764
>char* argv[]
absolutely disgusting
>>
>>61743764
>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.
>>
>>61743764
>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
>>
File: 1487394948306.jpg (16KB, 600x450px) Image search: [Google]
1487394948306.jpg
16KB, 600x450px
>>61743634
>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.
>>
>>61743816
>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.
>>
>>61743798
>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.
>>
>>61744157
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.
>>
>>61743798
>>61744157

#
# 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
>>
>>61744213
Just POO my shit up.
>>
>>61744209
>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.
>>
>>61742378
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...
>>
>>61743107
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?

>>61743123
> 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?

>>61743634
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.
>>
>>61744407
>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.
>>
>>61744467
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?
>>
>>61744534
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.
>>
>>61744407
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
>>
>>61744622
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)
>>
>>61741232
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.
>>
File: Richard Stallman.jpg (105KB, 480x320px) Image search: [Google]
Richard Stallman.jpg
105KB, 480x320px
>>61744797
>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.
>>
>>61744825
I wonder if he ever thought how you are going to make a living when you don't get paid for your work?
>>
>>61744797
>> constant variables
:(
>>
>>61744797
>> switch case
dude dicts lmao
>>
File: picdump-17-06-16-042.jpg (85KB, 600x600px) Image search: [Google]
picdump-17-06-16-042.jpg
85KB, 600x600px
>>61744879
If you work for a company, the company owns the source-code anyways. Same if you are a contractor that develops Software.
>>
>>61744797
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.
>>
>>61744770
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.
>>
>>61745222

So it's more like "+" is a function that get passed on through currying?
It's been a while since I used functional programming.
>>
>>61744797
>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)
>>
>>61744797
>constant variables
Makes no sense.
>do while
https://www.python.org/dev/peps/pep-0315/
>switch case
https://www.python.org/dev/peps/pep-3103/
>>
>>61745268
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
>>
>>61744982
>a fascist
Nani?
>>
>>61744261
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.
>>
>>61744576

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?

>>61744622
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.
>>
>>61743489
(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?
>>
>>61744576
>>61747170

I think you are misunderstanding. Too lazy to type it out again, nobody cares anyway.
>>
>>61745282
I like python, but it's lambda syntax is rather limited, although you can achieve quite a bit with comprehensions.
>>
>>61747231
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.
>>
>>61747170
>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
>>
>>61747580
One of the many reasons I love Python. I just wish it was faster. But oh well, simplicity also has its downsides apparently.
>>
>>61743574
>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
>>
>>61747580
You can dllimport an EXE.
>>
>>61748007
So? An EXE can have symbols too,
>>
>>61741232

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
>>
>>61745282
I like it except there is no default
>>
>>61742868
Why is that stuff even important? Even if you dislike it it's just a minor inconvenience. Holy shit I wonder when people on /g/ discuss about non-trivial shit.
People like you make me think that 90% of /g/ are either in high school or in the first semester of college.
>>
>>61741965
public static void main(String[] args)
Oh yep much more intuitive
>>
>>61747170
>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
>>
>>61751567
>Holy shit I wonder when people on /g/ discuss about non-trivial shit.

It's like I said in >>61743520 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.
>>
>>61751656
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.
>>
>>61751518
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)
>>
>>61747340
>try nested lambdas
>>
>>61741232
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.
>>
>>61752704
/thread
>>
>>61741928
>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
}())
>>
>>61753686
Anything written in the top level will be executed when the module is imported
https://stackoverflow.com/questions/37325667/does-es6-module-importing-runs-the-code-inside-the-file
>>
>>61753735
Oh dear christ what fucking idiot thought this was a good idea?

Here I was thinking ES6 was generally going the right direction.
>>
>>61753760
As already mentioned in >>61741928 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.
>>
>>61753760
It is a GREAT idea you dumb cunt
Thread posts: 96
Thread images: 6


[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y] [Search | Top | Home]

I'm aware that Imgur.com will stop allowing adult images since 15th of May. I'm taking actions to backup as much data as possible.
Read more on this topic here - https://archived.moe/talk/thread/1694/


If you need a post removed click on it's [Report] button and follow the instruction.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com.
If you like this website please support us by donating with Bitcoins at 16mKtbZiwW52BLkibtCr8jUg2KVUMTxVQ5
All trademarks and copyrights on this page are owned by their respective parties.
Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
This is a 4chan archive - all of the content originated from that site.
This means that RandomArchive shows their content, archived.
If you need information for a Poster - contact them.