8 ms·
Leaving Python for JavaScript
- dagenleg 9y ago> there's no acceptable way to pass a function body to another in Python. What. Why would you ever want a function body as a string? What kind of vile sorcery are you doing? One can use inspect.getsourcelines in python if really pressed to, but I find it horrifying that javascript developers actually seem to require this functionality often.
- rhodysurf 9y agoI cant figure out what he means either since he follows it up talking about map() and reduce() whcih you can use with function pointers (references? IDK what they actually are in python)
- dagenleg 9y agoI edited my post, as after giving it some thought I concluded that the author wants to pass around the source code of the function. That indeed is something that python cannot provide in cases when function is already precompiled.
- deleted 9y ago[deleted]
- zeugmasyllepsis 9y agoI'm guessing, since the author used the arrow shorthand notation in Javascript as an example, that the limitations of Python's lambdas are the chief complaint
- dagenleg 9y agoIt's more of a feature than an arbitrary limitation I think. Python philosophy, 'explicit over implicit', and that stuff.
- zeugmasyllepsis 9y agoAn intentional limitation, then :P I tend to agree with the Python philosophy, that it's usually better to extract and name a function that to declare it inline. The `asyncio` module and `await` keywords go a long way in eliminating most use cases where I'd still prefer an anonymous function, for arbitrary callbacks.
- saurik 9y agoThe author did not say "as a string" and I am extremly confused as to how you read it like that... what? Essentially, the complaint (which is extremely common) is that functions that contain statements are not expressions in Python, so functional coding styles using things like .map() and .reduce() end up fragmented (and you are horribly tempted to play extremely insane tricks with decorators to build something that feels like a Frankenstein Ruby block); this is why the author then brings up arrow functions: it has nothing to do with strings.
- dagenleg 9y agoWell truth be told it was hard for me to understand what the author meant. Thanks for clarification.
- deleted 9y ago[deleted]
- aaronchall 9y ago> the complaint (which is extremely common) is that functions that contain statements are not expressions in Python, so functional coding styles using things like .map() and .reduce() end up fragmented You mean these critics find >>> map(lambda x: x**2, filter(lambda x: not x % 2, range(11))) preferable to the "fragmented": def square(x): return x ** 2 def is_even(x): return not x % 2 >>> (square(x) for x in range(11) if is_even(x)) Both result in the same lazy iteration (to see results below - requires materialization with a constructor like list or tuple), but I find the "fragmented" approach much more readable (so long as the functions do what their name says they do - I have seen Python where they actually did the opposite...) >>> list((square(x) for x in range(11) if is_even(x))) [0, 4, 16, 36, 64, 100] >>> list(map(lambda x: x**2, filter(lambda x: not x % 2, range(11)))) [0, 4, 16, 36, 64, 100]
- hinkley 9y agoProgrammers are terrible at naming things and we copy each other's mistakes. In the real world you filter water to get the water. In most programming languages filter() is more like a strainer or colander. My guess is you ran into someone stubbornly insisting on the meaning of the word filter despite all evidence.
- kronos29296 9y agoHigher order functions maybe? Though python has them. Spread operator can be done as unpacking a list. Destructuring assignment can also be done. Map is already there while reduce is in functools stdlib. So are all the other functional stuff. Async is in python 3. Can't say what python lacked except being able use same language on front end and back end. Except if he still uses python 2 which hasn't any new features in years.
- ojhughes 9y agoPoor misguided person
- crimsonalucard 9y agoI use to read hacker news and feel that all the articles were by people infinitely smarter than me. Nowadays I occasionally hit something like this. The fact that this makes it to the front page means many programmers are equally misguided...
- creatonez 9y agoThen guide the OP yourself. Posting short inflammatory comments isn't going to change how people approach the topic.
- rdudekul 9y agoA lot of innovation happened in JavaScript space over the past few years and yet the learning curve is high. I prefer to use Python for Data Analysis, Data Transformations & Machine Learning. For web applications, Node/Express + React/Vue seems to work better.
- jgalvez 9y agoYep, Python is still king for machine learning.
- deleted 9y ago[deleted]
- monkmartinez 9y agoI started programming in JS then moved to Python. It seems like JS has become very, very complicated. I look at his post and I am lost... I remember Knockout.js and Node in the v0.8 days. I mean look at this: dotenv (lets you load the environment from an .env file), axios (HTTP client library), cheerio (HTML parsing library), bcrypt (password hashing), co-body (HTTP body parser), co-busboy (HTTP multipart parser), jsonwebtoken (JWT generator), koa-jwt (JWT middleware), koa-router, koa-sslify, vue-no-ssr and source-map. What the hell is all that? I am not saying he is wrong... I am just saying that I don't have the capacity to play in that playground. I am also asking if any of those libraries will be around in a year?
- alayek 9y agoI have been in your position about a year ago. The approached that helped me, was to not worry about all this. Just start somewhere; and in a month or two, you would mostly know which libraries you need to add to your project. The best way to go about it, is to check a few popular open source projects; what libraries they typically use. > I am also asking if any of those libraries will be around in a year? You can check the download stats of these in https://npmjs.com https://npmjs.com, and activity on the GitHub repo, before adding it to your project. If they are still around, but have published a new major version to update a few APIs; you can slowly migrate to it. If not, you'd read some Medium post or Hackernews discussion, about what is replacing that. There's something called Greenkeeper (https://greenkeeper.io/ https://greenkeeper.io/) that integrates a GitHub bot to your repo, and files a PR when something needs to be upgraded. You can implement something similar on your own, if you aren't interested in using something like this.
- secstate 9y agoI mean no offense, but the "just use it you'll get used to it" strategy seems the antithesis of the goal of engineering as a discipline. A materials engineer simply cannot afford to pick concrete unless she knows the specific load and weathering characteristics of it. The same should be true for software projects. You shouldn't use cheerio because everyone uses it in their project, but because you've looked through the source and considered all your options for need it fills. Sorry for the rant, but I think it's important to encourage software developers to think before they code.
- metaphorm 9y agowhy is the sidebar on the left half the width of the page? I can hardly read the main content crammed into the right half.
- dharness 9y agoWhy is all the actual content on the far right side of the page? Even more interesting given that you specialize in UI/UX.
- jgalvez 9y agoHi, it's just a blog, not a paid job. Not a lot of effort went into it. I'll take a look when I have a chance (it looks fine on my MBP and several others).
- sushisource 9y agoI don't think it's broken. It just looks pretty cramped and weird if you've got your browser in a portrait orientation.
- jp_sc 9y agoWhy not? In what way this is worse than having the same column of content centered or on the left side of the page? I find it refreshingly different.
- Walkman 9y ago> there's no acceptable way to pass a function body to another in Python. There are sentences which are telling a huge incompetence about the person using these. This sounds the same story to me as "We used tech X, but X is shit/can't do something so we switched to Y, and Y is awesome and fast." Where the person switching was just incompetent with X but it would have been perfectly solvable and they just do a totally different thing with Y. In the specific "passing a function" case, yes, it's impossible to pass only a function body, but I think it's impossible to do in JavaScript also? (correct me if I'm wrong), because you pass in function. You can do the same in Python by defining a function in the same scope and passing that in. If you don't like that, it's just one opinion, not necessarily good or bad. For example, I find it ugly and difficult to handle nesting this multiple times (defining another anonymous function inside an anonymous function) which is called "callback hell" if I understand right, but that's just my opinion also, because people seem to able to accept this hell. :)
- neurotrace 9y agoNo one likes callback hell but I believe they meant that you can just pass a function expression directly. No need to define a named function. It's the difference between: let doubled = nums.map(x => x * 2) and this: def double(x): return x * 2 doubled = map(double, nums) (my Python is pretty rusty so maybe there's a better way of doing that)
- takeda 9y agoYou can do the exact same thing in Python, and this is not any new feature: doubled = map(lambda x: x * 2, nums) JS it's just not as explicit with what you're exactly doing.
- gknoy 9y agoIf you want more than a one-line lambda, however, you're in for a rough time, and need to go the route of def foo(): # ... four lines here ... modified = map(foo, items)
- freecodyx 9y agoI did the move but to GOLANG instead. I think what is more important than the language it self, is the toolings and standard library. every now and then you hear about a new framework, a lot of hype, which is not for big projects. I think the wise thing is to move to golang
- monkmartinez 9y agoWhy? I mean please elaborate.
- jjnoakes 9y agoI want to like JavaScript, but the type coercion land mines and the lack of a real numeric tower make me a little queasy. When I have to use JS I stick to the transpile-to-js languages mostly for those reasons.
- scriptkiddy 9y agoJust in case the author is present in the thread: Your blog is extremely difficult to read on wide screen monitors. The entire left 50% is basically just blank space. My suggestion is to make the left side maybe 20% width on desktop or less. Also, regarding the article content: There really aren't any good reasons presented here about why you moved from Python to Javascript for back-end web development. It seems that you simply prefer Javascript semantics. There's nothing wrong with that, but the title is misleading considering that the bulk of the article is actually about which JS tools you use on recent projects and not why you moved. Also, could you clarify what you mean by > Also, there's no acceptable way to pass a function body to another in Python. Functions are first-class in python and can be passed as arguments to other functions. I'm not sure I understand what you mean with the above statement. Cool to see someone else has been using Nuxt though.
- haikuginger 9y ago> Functions are first-class in python and can be passed as arguments to other functions. I'm not sure I understand what you mean with the above statement. I believe the author is referring to inline definition: setTimeout(function(){alert("Timed out!");}, 5000) You can do something similar with lambdas in Python, but the allowed syntax is relatively limited compared to a full function definition. You could also define an inline function, but it'd be in a separate statement from the call you make with it. Unfortunately Python doesn't allow for creating and returning a first-class function in a single expression.
- 9t3h4r3o5w1a4w2 9y agoPython has lambda but they are one liners. There is no way to do write this in Python: someFunc( _ => { // this is // a function // with multiple lines }) Having to define a named function to use it as a callback is a pain in the ass. Python has an excellent standard library but the language itself is pretty mediocre IMHO. Classes are an afterthought thus verboses, as so is "functional programming" in Python. JS biggest issue is that it is not strongly typed enough. But ES2015 makes it really pleasant to use.
- 9y ago
- edem 9y agoI was going to suggest that the you have to be lobotomized to do something like this then I remembered that perfectly OK folks decide to go to places like North Korea (and come back lobotomized) so now I only suggest that you must be extremely inexperienced to dump python for javascript...I mean js doesn't even have a proper stdlib nor any means for quality control over what gets into the npm archives. No wonder that you have a new library for X in every week just to be forgotten the next month.
- ageitgey 9y agoSo a person who writes web apps prefers JS over Python. Cool. Pick the right tool for the job. If your job is writing client-side-heavy web apps that share code between the client and server, then JS might be a better choice than Python. Look, writing programs that respond to HTTP requests with HTML is not rocket science. You can do it in JS, Python or Ruby and be very productive. If you hate yourself, you can do it in Java, Go or whatever else and trade server performance for development speed. If you really hate yourself (or are Amazon circa 2004), you can write your whole website as a C++ static binary. My theory is that the endless proliferation of JS libraries, frameworks and language revisions are because lots of smart and talented developers are employed to build websites - but building websites is just not that technically interesting, so they express their creativity by creating new tools, frameworks, package managers and ES revisions. It's a symptom of boredom. But my one bit of career advice would be don't "Leave X for Y." Don't tie your livelihood and career to a single X or Y. Learn how to use a variety of tools and pick the best one for each job. Any big project will require using a few different tools and really valuable developers are the ones who can navigate that entire landscape intelligently.
- jgalvez 9y agoAll very well said. I never said I was leaving Python for good, in fact, it needs to be pointed out it's still king for machine learning and I'll even integrate a Python-based solution as microservice to a Node.js project. Perhaps a clearer title would have been, "JavaScript is now my main language". As for boredom, though, it's true, but every now and then something special emerges out of boredom, as was the case for Vue.js and most recently, Nuxt.js for me. I hate the amount of JS frameworks and libraries available like everybody else and if anything, this article is also a short reference for myself in disguise on _how to get started_. I'll say though, knowing your way around a Node.js project can be painful, but with a little experience can become really reassuring. Code runs fast, it's easy to write (easy idioms to memorize like Python) and is generally very predictable.
- rlander 9y agoRight? When I read these kind of posts I always imagine a carpenter saying the equivalent "After over 10 years using a hammer as my main tool, I have moved on to the screwdriver." Which is nonsense.
- holydude 9y agoI am still learning to like Javascrip and its ecosystem. I do not think I would be able to invest time in transpile-to-js language (looking at you TypeScript). I really hate the evolving ecosystem, hyped libs / frameworks and tons spaghetti new paradigms.
- creatonez 9y ago>I really hate the evolving ecosystem, hyped libs / frameworks and tons spaghetti new paradigms. Then don't use them. The javascript ecosystem on the backend and frontend has settled down quite a bit. Use something that's been established for a while (React, Vue on frontend or Express, Koa on backend) and you're not gonna suffer from churn too badly.
- devnonymous 9y ago> So with JavaScript you've got arrow functions, the method shorthand definition syntax, the spread operator, destructuring assignments, all functional Array methods and async functions. In language that pythonistas would grok: Arrow functions: multiline lambda definitions method shorthand definition syntax: class defined with only classmethods, or in other words a namespace the spread operator: *args in functions destructuring assignments: tuple unpacking... But also for creation of instances all functional Array methods and async functions: functools and async... Plus a bit more While most of this is good to know, I'd still stick with python for readability and maintainability purposes.
- creatonez 9y agoIMO arbitrary rules like lambda expressions being limited to one expression do not directly improve readability and maintainability. Consistently using good conventions in the first place will help you more than arbitrary restrictions. And to be clear, I would classify, say, Rust as not having many arbitrary restrictions. All the limitations that Rust has compared to C fit clearly within the language's core design. On the other hand, I don't see this same structure and consistency to some of Python's rules.
- dragonwriter 9y ago> IMO arbitrary rules like lambda expressions being limited to one expression do not directly improve readability and maintainability. In Python’s specific case, I've seen no alternative that isn't bad for readability; the strong line-orientation of Python's broader syntax limits the good options for inline anonymous functions. That being said complex lambdas in general can be adverse to maintainability and Python’s single-expression limitation largely prevents that (though you can make hideously complex opaque single-expression lambdas if you try.)
- wolco 9y agoIf you started with php instead of python you would never have left. Vue is a great language but php can offer more in the backend
- kochandy 9y agoThanks for your article. It's really helpful to hear about the technologies that have been used in actual projects/production environments. I'd love to hear more about what diminished your excitement with ElementUI vs iView
- jgalvez 9y agoMostly aesthetics in the default theme. Both are actively maintained and the APIs are super similar.
- yiransheng 9y agoES6+ javaScript in absorbed many great features from python: destructuring vs. tuple unpacking, spread (...) vs *args argument unpacking and generators. Many things I enjoyed in python are now also idiomatic javaScript. Only thing missing is function decorators: @connect(...) function StateLessComponent(props) { }
- deathanatos 9y ago> the spread operator How? JS: var args = [0, 1, 2]; myFunction(...args); Python: args = [0, 1, 2] myFunctions(*args) A more complicated one: JS: var args = [0, 1]; myFunction(-1, ...args, 2, ...[3]); Python: args = [0, 1] myFunction(-1, *args, 2, *[3]) As used in list building; JS: var parts = ['shoulders', 'knees']; var lyrics = ['head', ...parts, 'and', 'toes']; Python: parts = ['shoulders', 'knees'] lyrics = ['head', *parts, 'and', 'toes'] "A better way to concatenate arrays"; JS: var arr1 = [0, 1, 2]; var arr2 = [3, 4, 5]; arr1 = [...arr1, ...arr2]; Python: arr1 = [0, 1, 2] arr2 = [3, 4, 5] arr1 = arr1 + arr2 (Though the star notation works here too.) I omit JS's use of ... on objects; Python's class system works differently — and IMO, more rigorously — than JS's, making ... less sensible on Python objects. (Python focuses much less on passing around untyped key-value bags and more on strongly typed classes IMO; both are possible in both languages, but the idioms around them differ, and I think Python's idioms tend more towards having a well defined class with well defined attributes, and not having just a bag of attributes, moreso than JS at least, and I feel that direction (well defined classes) leads to more robust code. In particular, it forces you into naming your concepts, and defining their set of attributes: a simplistic type definition.) > all functional Array methods Python has map, reduce, etc., as well as generator and list comprehensions which are often easier to use. > async functions Python and JavaScript have practically identical syntax in this area. > there's no acceptable way to pass a function body to another in Python I find it very acceptable that if your function body is more complicated than an expression, that you're forced to pull it out and name it, frankly. I think it does good things for fighting complexity, and this just isn't something I worry about day to day while using Python. But I will concede that Python does lack a syntax for passing a function in an expression context. (But I would also note JS's screwed up named-function syntax; in Python: def foo(): # body is a valid statement. JS's: function foo() { // body } is not a valid statement, and can only appear in certain, particular contexts. In particular, the following is not valid JavaScript, though many implementations will do The Right Thing™, I'm told: if(true) { function foo() { // body. } } [2]) > My code usually revolves around higher order functions, reduce(), map(), etc. I can't remember the last time I wrote a regular for loop in JavaScript. Because JS for a long time (until ES6's for(… of …) syntax) lacked a for loop (the C style look, and for(… in …), do not count, as they do semantically different things), which is why you're using forEach(). > arrow functions The best thing about arrow functions is the sane binding of `this`, a problem notably absent in Python to begin with. > [Python's] class definition boilerplate is still hard to look at This is sometimes true; I find the attrs[1] package helps greatly here for small, struct-like classes. [1]: https://pypi.python.org/pypi/attrs https://pypi.python.org/pypi/attrs [2]: http://kangax.github.io/nfe/#expr-vs-decl http://kangax.github.io/nfe/#expr-vs-decl
- abuckenheimer 9y ago> So with JavaScript you've got arrow functions, the method shorthand definition syntax, the spread operator, destructuring assignments, all functional Array methods and async functions. This confuses me quite a bit, there are nuanced differences between these ideas in the two languages but at the surface these are things that very much exist in both languages arrow functions: (x,y) => { x + y } vs. lambda x,y: x + y method shorthand definition: MyObj = { foo(x,y) { return x + y } bar(x,y) { return x * y } } vs. class MyObj: foo(self, x, y): return x + y bar(self, x, y): return x * y spread operator: function add(x,y) { return x + y } add(...[1,2]) vs. def add(x, y): x + y add(*[1,2]) destructuring: [a, b, ...rest] = [10, 20, 30, 40, 50]; vs. a, b, *rest = [10, 20, 30, 40, 50] functional array methods: forEach(["Wampeter", "Foma", "Granfalloon"], print); vs. list(map(print, ["Wampeter", "Foma", "Granfalloon"])) async methods: function resolveAfter2Seconds(x) { return new Promise(resolve => { setTimeout(() => { resolve(x); }, 2000); }); } async function add1(x) { var a = resolveAfter2Seconds(20); var b = resolveAfter2Seconds(30); return x + await a + await b; } add1(10).then(v => { console.log(v); // prints 60 after 2 seconds. }); vs. async def resolve_after_2_seconds(x): await asyncio.sleep(2) return x async def add1(x): a = resolve_after_2_seconds(20) b = resolve_after_2_seconds(30) return x + await a + await b loop = asyncio.get_event_loop() loop.run_until_complete(add1(10)) There's a lot of fun differences between the origins of these features and how they work but the sentence to me doesn't quite to the idea of "Leaving Python for JavaScript" justice
- deleted 9y ago[deleted]
- _greim_ 9y agoWith async/await now landing in mainstream engines, Koa instead of Express, the new Turbofan+Ignition optimization pipeline "evening out" V8's performance characteristics, and ES6 enjoying reasonably broad support, I feel like JS is now crossing a threshold into being not a completely sucky programming experience, which is a sentiment this article echoes. I'm probably being overly optimistic, but I look forward to a future where a "naked JS" movement rises up, similar to "vanilla JS", but rebelling against tooling complexity instead of jQuery bloat, in which your website's /js/ folder contains pretty much exactly what's in git.
- spondyl 9y agoI'm split on it myself. I like being able to go Right Click -> View Source and poke around but with more modern sites, you're given nothing but a single JS file. You can scroll through the DOM in developer tools but it's not as neat as text :(
- yupyup 9y agoWhen reading these "Leaving X for Y" I first think that maybe some people are unable to fluently use more than 1 language. Seriously, professionality is being able to use the right tool for the job at hand.
- vitamincandle 9y ago> There are sentences which are telling a huge incompetence about the person using these. Having "worked" with Jonas Galvez, I can tell you that he is hugely incompetent in all sorts of other ways as well. From skipping conference calls to writing completely broken code, he single-handedly drove down the productivity of our entire team. We paid him, but we learned to never trust anybody that's willing to work for free.[1] [1] https://news.ycombinator.com/item?id=7326682 https://news.ycombinator.com/item?id=7326682
- jgalvez 9y agoLike any other developer out there, I collected some bad experiences in my growth. In my 14-year career, 2015-2016 were spectacularly bad years for me, definitely the worst. It has to do with focus and productivity, not competence. I must say I didn't think it was so bad as to leave this kind of sentiment behind. If you worked with me in that period, perhaps you'll be pleased to read this: http://hire.jonasgalvez.com.br/2017/Jul/16/My-Approach-to-Remote-Work http://hire.jonasgalvez.com.br/2017/Jul/16/My-Approach-to-Re... Since then I'm confident all my current employers will wholeheartedly vouch for the quality and persistence of my work, as you can easily peak from my GitHub graph. http://github.com/galvez http://github.com/galvez I flagged your post nonetheless. I believe HN is no place for ad hominem attacks.
- Walkman 9y agoI don't know how to say it without you taking it as a personal attack, but I think it's important to say so you can take the opportunity and learn or at least think about it; If you say things like that I quoted, you are incompetent and you have to learn a lot. I feel I have to say this because you send the wrong message to a wider audience which I really hate. Also I skimmed your library httplib2 and it's at least terrible to read. Again, you can take this as a personal attack, flag this comment also, be mad or whatever, or buy Clean Code and start reading, also start learning more about Python idioms from people who are really good at it, e.g. Raymond Hettinger, Armin Ronacher
- jgalvez 9y ago