>  기사  >  웹 프론트엔드  >  풀스택 개발: JavaScript 개발자로서 Python 배우기

풀스택 개발: JavaScript 개발자로서 Python 배우기

WBOY
WBOY원래의
2024-08-31 00:22:33462검색

Fullstack Development: Learning Python as JavaScript Developers

여행이 시작됩니다

저는 8년 넘게 프론트엔드 개발자로 일해 왔으며 지난 2년 동안 제 경력과 제가 어떻게 성장할 수 있는지 다시 생각해 보기로 결심했습니다. 저는 프론트엔드 기술이 자주 바뀌는 것을 발견했습니다. 다양한 프레임워크, 개념, React 클래스 구성 요소와 후크 간의 격차 등이 있었습니다. 나는 이 모든 것이 비즈니스 요구와 개인적인 비전을 표현하기 위해 사용되는 추상화에 불과하다는 것을 깨달았습니다. 이때부터 진로를 바꿔 조금은 풀스택 개발자가 되기로 결심했습니다.

우리 모두 알고 있듯이 요즘 프론트엔드 개발은 JavaScript에 관한 것입니다. 그래서 저는 Node.js와 그 주요 프레임워크를 배우기로 결정했습니다. 모든 프런트엔드 개발자는 어떤 방식으로든 Node.js를 접하게 되며, 선임 프런트엔드 개발자라면 Express나 다른 라이브러리를 사용하여 Node.js에 기본 엔드포인트를 작성할 수 있어야 합니다. Node.js 측에서 2년 동안 활발한 개발을 한 후, 내 직업이 프런트엔드와 백엔드 사이에서 50/50이 되었을 때, 나는 대부분의 프로젝트가 단지 하나의 언어에만 국한되지 않는다는 것을 발견했습니다.

Node.js는 모든 것에 이상적인 도구는 아니며, 특히 대규모 회사에서 일하는 경우에는 더욱 그렇습니다. 다양한 언어는 다양한 솔루션을 제공하거나 특정 비즈니스 사례를 해결하는 데 더 적합합니다. 그래서 제2의 백엔드 언어로 무엇을 배울 수 있는지, 앞으로 어떻게 활용할 수 있을지 연구하기 시작했습니다.

내 경험과 Rust(주로 웹 개발용이 아님), Swift(주로 모바일 우선 솔루션), Golang을 배우려고 노력한 후 Python을 계속 사용하기로 결정한 이유를 공유하고 싶습니다. 여기에서 제가 Python이 프런트엔드 개발자에게 Python을 배우고 사용하는 방법을 배울 수 있는 좋은 기회라고 생각하는 이유를 알아보실 수 있습니다.

왜 파이썬인가?

요즘 AI는 모두의 화두입니다. 경험의 일부로 인터뷰에서 이를 언급하면 ​​항상 추가 포인트를 얻을 수 있습니다. 거의 모든 회사가 AI를 제품에 통합하려고 노력하고 있으며 Python은 AI 및 기계 학습과 함께 사용됩니다. Python을 배우면 Django, Flask, FastAPI와 같은 프레임워크를 사용하여 웹 애플리케이션을 작성할 기회를 얻을 수 있을 뿐만 아니라 머신 러닝 및 AI 서비스 작업을 시작할 수도 있습니다.
한편으로는 더 나은 프로그래머가 되고 싶다면 Rust, Go 또는 Elixir와 같은 더 복잡한 언어를 배우는 것이 좋은 생각입니다. 하지만 경력 측면에서 볼 때 익숙하지 않은 전혀 다른 언어를 사용하는 백엔드 개발자로의 전환은 쉽지 않습니다.

Python은 동적 유형 프로그래밍 언어입니다. 유사한 환경에서 경력의 상당 부분을 보낸 JavaScript 개발자로서 코드에서 어떤 종류의 문제가 예상되는지 이미 알고 있으므로 이것이 겁나서는 안 됩니다.
Python을 사용하면 웹 애플리케이션 작성을 시작할 수 있을 뿐만 아니라 AI 관련 분야의 기술을 활용할 수 있으므로 Python이 제2 언어로서 상당한 이점을 얻을 수 있습니다.

학습 곡선

학습 곡선은 간단했습니다. Python에서는 몇 가지 기본 개념을 확실히 배워야 합니다. JavaScript를 사용해 본 경험이 있다면 별 문제가 되지 않습니다.

다음은 Python의 코드 예제입니다.

import random

def guess_the_number():
    number_to_guess = random.randint(1, 100)
    attempts = 0
    guessed = False

    print("Welcome to the Number Guessing Game!")
    print("I'm thinking of a number between 1 and 100. Can you guess what it is?")

    while not guessed:
        user_guess = int(input("Enter your guess: "))
        attempts += 1

        if user_guess < number_to_guess:
            print("Too low! Try again.")
        elif user_guess > number_to_guess:
            print("Too high! Try again.")
        else:
            print(f"Congratulations! You guessed the number {number_to_guess} in {attempts} attempts.")
            guessed = True

guess_the_number()

여기에서는 그다지 복잡한 내용을 찾을 수 없을 것 같습니다. 이전에 Python을 배운 적이 없더라도 설명서를 읽지 않고도 거의 모든 줄을 이해할 수 있습니다.

눈에 띄는 가장 큰 차이점은 Python이 코드 블록을 정의하기 위해 중괄호 대신 들여쓰기를 사용한다는 것입니다. 이상하게 보일 수도 있고 여전히 조금 이상하다고 생각하지만, 시간이 지나면 익숙해지고 코드 읽기가 더 쉬워집니다.

그 외에도 Python의 많은 개념은 JavaScript의 개념과 유사합니다. console.log 대신 print를 사용할 수 있으며, 문자열 보간을 위해 문자열 시작 부분에 f를 추가하면 JavaScript와 거의 동일한 구문을 사용할 수 있습니다.

위 코드의 JavaScript 버전은 다음과 같습니다.

function guessTheNumber() {
    const numberToGuess = Math.floor(Math.random() * 100) + 1;
    let attempts = 0;
    let guessed = false;

    console.log("Welcome to the Number Guessing Game!");
    console.log("I'm thinking of a number between 1 and 100. Can you guess what it is?");

    while (!guessed) {
        const userGuess = parseInt(prompt("Enter your guess: "), 10);
        attempts++;

        if (userGuess < numberToGuess) {
            console.log("Too low! Try again.");
        } else if (userGuess > numberToGuess) {
            console.log("Too high! Try again.");
        } else {
            console.log(`Congratulations! You guessed the number ${numberToGuess} in ${attempts} attempts.`);
            guessed = true;
        }
    }
}

guessTheNumber();

장애물 극복: 주요 개념

파이썬에서는 다양한 개념을 배울 수 있습니다. 자바스크립트 개발자로서 가장 혼란스러운 모습을 보여주었습니다.

들여쓰기 기반 구문

JavaScript 개발자라면 if/else 및 기타 연산자와 함께 코드 블록을 사용하는 방법에 익숙할 것입니다. 대부분의 경우에는 {}만 추가하면 됩니다. Python의 들여쓰기 기반 시스템은 까다로울 수 있습니다.

JavaScript 코드를 살펴보겠습니다.

if (role === "admin") {
    const posts = getDraftPosts()

    if (posts.length === 0) {
        throw NotFound()
    }   

    return posts
}

Python 아날로그:

if role == "admin":
    posts = get_draft_posts()

    if posts.length == 0:
        raise NotFound()

    return posts

As you can see readability of blocks in Python could be challenging from the first view. This is why for me it was important to avoid deeply nested blocks because it is hard to read and easy to miss correct indention. Keep in mind that Python could attach your code to a wrong code block because of missed indention.

Type system

Python is a dynamic typing language but I was surprised to find Python built-in Types annotation.

def add(x: int, y: int) -> int:
    return x + y

You don’t need to install additional features, only what you need in Python *3.5 and above.*

Even more complex types could be described as equal to Typescript:

# enums
from enum import Enum # import enum for built in lib

class Season(Enum): # extend class to mark it as enum
    SPRING = 1
    SUMMER = 2
    AUTUMN = 3
    WINTER = 4

print(Season.SPRING.name) # SPRING
print(Season.SPRING.value) # 1

# or generics
def first(container: List[T]) -> T:
    return container[0]

list_two: List[int] = [1, 2, 3]
print(first(list_two)) # 1

For using these types you are not required to install something or transpile this code. This is something I missed in JavaScript, at least Node.js. I know Node.js is adding some basic types in the nearest version (see Medium post about node.js built-in types support) but it looks poor now if you compare it with Python.

Python’s Global Interpreter Lock (GIL)

JavaScript uses an event-driven, non-blocking model, while Python's Global Interpreter Lock (GIL) can be a confusing concept in multi-threaded programs.
The Python Global Interpreter Lock (GIL) is a mechanism that ensures only one thread executes Python code at a time. Even if your Python program has multiple threads, only one thread can execute Python code at a time due to the GIL.
With JavaScript, you can achieve multithreading with web workers, but in Python, you need to use additional libraries to accomplish this.

A Pythonic Mindset

JavaScript's "multiple ways to do it" philosophy doesn't work as well in Python because Python adheres more closely to the concept "There should be one - and preferably only one - obvious way to do it."
In the JavaScript world, every company often creates its own code style guide, and it's fortunate if it follows basic JavaScript style recommendations. In reality, practices like using semicolons can vary widely, to the point where one project might use semicolons and another might not.
In Python, following Pythonic principles from PEP 8 (Python's style guide) is highly recommended. This guide outlines the basic rules of how to write Python code.
To write better code, it's essential to engage with the community and learn idiomatic Python practices that prioritize clarity and simplicity.

Managing Dependencies and Virtual Environments

This part might also be confusing. In JavaScript, you can usually add a package manager and start installing dependencies without any issues. However, Python’s pip and virtual environments may be new concepts.

In Python, when using additional dependencies, it’s highly recommended to use a separate virtual environment. Installing dependencies with pip (the Python equivalent of npm in JavaScript) in your environment could potentially break system utilities or the OS itself, as the system Python interpreter (the one that comes pre-installed with your operating system) is used by the OS and other system utilities.

As a solution, you can create a virtual environment with venv module:

python -m venv myenv
myenv\Scripts\activate # for windows
source myenv/bin/activate # for Mac

After you enter the virtual environment you can install all dependencies without any problem or danger for your root environment.

Finding Support and Resources

How I Learned Python

Learning a new language is always challenging. I started learning Python basics on an online platform, where I also completed some small projects. Here is the plan I used during my learning process:

  • Python basics.
  • Advanced Python concepts (module system, types, environment, async code).
  • Learning the basics of the most popular frameworks like Django, Flask, and FastAPI.
  • Writing my first API server with FastAPI.
  • Adding a database and learning how to work with databases in Python.
  • Deploying the application on a free hosting service.

Where to Find Help

You can find a lot of help in Reddit communities or Discord servers while learning. I’m mostly a Reddit user and would suggest finding subreddits for Python and the framework you decide to use for your first application.

Remember to use the official documentation. In my opinion, it looks overwhelming, and most of the time, I try to find related articles if I get stuck on a concept.

Make sure to read PEP 8 — Style Guide for Python Code, where you can find basic rules on how to write Python code.

뒤돌아보고 앞으로

JavaScript 개발자에서 Python을 수용하기까지의 여정을 되돌아보면 후회하지 않습니다. 이러한 전환으로 인해 특히 AI 및 기계 학습 영역에서 흥미로운 기회가 열렸으며 이제는 내 프로젝트, 특히 백엔드에서 이를 광범위하게 활용하고 있습니다.

앞으로 Python의 가능성은 무궁무진합니다. 웹 개발, 데이터 과학, 자동화, AI 및 기계 학습에 대한 심층 탐구 등 Python은 새로운 지평을 구축하고 탐색할 수 있는 강력하고 다양한 기반을 제공합니다.

위 내용은 풀스택 개발: JavaScript 개발자로서 Python 배우기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.