Data Science and Data Proicessing

Pydantic 초보자 가이드

데이터를 구문 분석하고 유효성을 검사하는 Python 패키지

8 월 10 일 · 7최소 읽기
~의 사진마크 바빈의 위에Unsplash

오늘 주제는 Python 유형 힌팅을 사용한 데이터 유효성 검사 및 설정 관리입니다. 우리는 Python 패키지를 사용할 것입니다.Pydantic런타임에 유형 힌트를 적용합니다. 사용자 친화적 인 오류를 제공하여 잘못된 데이터를 포착 할 수 있습니다. 공식 문서에 따르면 Pydantic은

“… 주로 검증 라이브러리가 아니라 구문 분석 라이브러리입니다. 검증은 목적을위한 수단입니다. 제공된 유형과 제약 조건을 준수하는 모델을 구축합니다.

즉, pydantic은 입력 데이터가 아닌 출력 모델의 유형과 제약을 보장합니다.”

이 자습서에는 세 가지 섹션이 있습니다.

  1. 설정
  2. 이행
  3. 결론

다음 섹션으로 이동하여 필요한 모듈 설치를 시작하겠습니다.

1. 설정

설치를 진행하기 전에 가상 환경을 만드는 것이 좋습니다.

기본 설치

터미널을 열고 다음 명령을 실행하여 설치하십시오.Pydantic

pip install pydantic

기존 패키지 업그레이드

이미 기존 패키지가 있고 업그레이드하려면 다음 명령을 실행하십시오.

pip install -U pydantic

아나콘다

Anaconda 사용자의 경우 다음과 같이 설치할 수 있습니다.

conda install pydantic -c conda-forge

선택적 종속성

Pydantic필요에 따라 다음과 같은 선택적 종속성이 제공됩니다.

  • 이메일 유효성 검사기— 이메일 검증을 지원합니다.
  • 타이핑 확장— 지원 사용정확한Python 3.8 이전.
  • python-dotenv- 을지 지하다Dotenv설정 파일.

수동으로 설치할 수 있습니다.

# install email-validator
pip install email-validator
# install typing-extensions
pip install typing_extensions
# install python-dotenv
pip install python-dotenv

또는 함께Pydantic다음과 같이 :

# install email-validator
pip install pydantic[email]
# install typing-extensions
pip install pydantic[typing_extensions]
# install python-dotenv
pip install pydantic[dotenv]
# install all dependencies
pip install pydantic[email,typing_extensions,dotenv]

2. 구현

이 섹션에서는 다음에서 사용할 수있는 몇 가지 유용한 기능을 살펴 보겠습니다.Pydantic.

개체 정의Pydantic에서 상속하는 새 클래스를 만드는 것만 큼 간단합니다.BaseModel. 클래스에서 새 개체를 만들 때Pydantic결과 모델 인스턴스의 필드가 모델에 정의 된 필드 유형을 따르도록 보장합니다.

수입

Python 파일 상단에 다음 가져 오기 선언을 추가합니다.

from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel

사용자 클래스

상속하는 새 클래스를 선언하십시오.BaseModel다음과 같이:

class User(BaseModel):
id: int
username : str
password : str
confirm_password : str
alias = 'anonymous'
timestamp: Optional[datetime] = None
friends: List[int] = []

Pydantic기본 제공 유형 힌트 구문을 사용하여 각 변수의 데이터 유형을 결정합니다. 무대 뒤에서 일어나는 일을 하나씩 살펴 보겠습니다.

  • 신분증— 정수 변수는 ID를 나타냅니다. 기본값이 제공되지 않으므로이 필드는 필수이며 객체 생성 중에 지정해야합니다. 문자열, 바이트 또는 부동 소수점은 가능한 경우 정수로 강제 변환됩니다. 그렇지 않으면 예외가 발생합니다.
  • 사용자 이름— 문자열 변수는 사용자 이름을 나타내며 필수입니다.
  • 암호— 문자열 변수는 암호를 나타내며 필수입니다.
  • 비밀번호 확인— 문자열 변수는 확인 암호를 나타내며 필수입니다. 나중에 데이터 유효성 검사에 사용됩니다.
  • 별명— 문자열 변수는 별칭을 나타냅니다. 필수 사항은 아니며 객체 생성 중에 제공되지 않으면 익명으로 설정됩니다.
  • 타임 스탬프— 필수가 아닌 날짜 / 시간 필드. 기본값은 없음입니다.Pydanticunix timestamp int 또는 날짜 / 시간을 나타내는 문자열을 처리합니다.
  • 친구— 정수 입력 목록입니다.

개체 인스턴스화

다음 단계는 다음에서 새 개체를 인스턴스화하는 것입니다.사용자수업.

data = {'id': '1234', 'username': 'wai foong', 'password': 'Password123', 'confirm_password': 'Password123', 'timestamp': '2020-08-03 10:30', 'friends': [1, '2', b'3']}user = User(**data)

인쇄 할 때 다음과 같은 출력을 얻어야합니다.사용자변하기 쉬운. 당신은 알 수 있습니다신분증입력이 문자열 인 경우에도 자동으로 정수로 변환되었습니다. 마찬가지로 바이트는 다음과 같이 자동으로 정수로 변환됩니다.친구들.

id=1234 username='wai foong' password='Password123' confirm_password='Password123' timestamp=datetime.datetime(2020, 8, 3, 10, 30) friends=[1, 2, 3] alias='anonymous'

BaseModel의 메소드 및 속성

상속하는 클래스BaseModel다음과 같은 메소드와 속성이 있습니다.

  • dict ()— 모델의 필드 및 값 사전을 반환합니다.
  • json ()— JSON 문자열 표현 사전을 반환합니다.
  • 부()— 모델의 전체 복사본을 반환합니다.
  • parse_obj ()— 객체가 사전이 아닌 경우 오류 처리를 사용하여 모델에 객체를로드하는 유틸리티
  • parse_raw ()— 다양한 형식의 문자열을로드하는 유틸리티
  • parse_field ()- 비슷하다parse_raw ()그러나 파일을 의미
  • from_orm ()— 임의의 클래스에서 모델로 데이터를로드합니다.
  • 개요()— 모델을 나타내는 사전을 JSON 스키마로 반환합니다.
  • schema_json ()— 다음의 JSON 문자열 표현을 반환합니다.개요()
  • 구성 ()— 검증을 실행하지 않고 모델을 생성하기위한 클래스 메소드
  • __fields_set__— 모델 인스턴스가 초기화 될 때 설정된 필드 이름 세트
  • __필드__— 모델 필드의 사전
  • __config__— 모델의 구성 클래스

입력을 변경하겠습니다.신분증다음과 같이 문자열에 :

data = {'id': 'a random string', 'username': 'wai foong', 'password': 'Password123', 'confirm_password': 'Password123', 'timestamp': '2020-08-03 10:30', 'friends': [1, '2', b'3']}user = User(**data)

코드를 실행할 때 다음 오류가 발생해야합니다.

value is not a valid integer (type=type_error.integer)

ValidationError

오류에 대한 자세한 정보를 얻으려면 다음과 같이 try-catch 블록 안에 래핑하는 것이 좋습니다.

from pydantic import BaseModel, ValidationError# ... codes for User classdata = {'id': 'a random string', 'username': 'wai foong', 'password': 'Password123', 'confirm_password': 'Password123', 'timestamp': '2020-08-03 10:30', 'friends': [1, '2', b'3']}try:
user = User(**data)
except ValidationError as e:
print(e.json())

다음 JSON을 출력합니다.신분증유효한 정수가 아닙니다.

[
{
"loc": [
"id"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]

필드 유형

PydanticPython 표준 라이브러리에서 대부분의 일반적인 유형을 지원합니다. 전체 목록은 다음과 같습니다.

  • 부울
  • int
  • 흙손
  • str
  • 바이트
  • 명부
  • 튜플
  • dict
  • 세트
  • 얼어 붙은
  • datetime.date
  • datetime.time
  • datetime.datetime
  • datetime.timedelta
  • 타이핑.
  • 타이핑 .TypeVar
  • 타이핑. 유니온
  • 입력합니다.
  • 타이핑. 목록
  • 타이핑. 튜플
  • 타이핑. 딕트
  • 타이핑. 세트
  • 타이핑 .FrozenSet
  • 타이핑. 시퀀스
  • 타이핑.
  • 타이핑. 유형
  • 타이핑.
  • 타이핑. 패턴
  • ipaddress.IPv4Address
  • ipaddress.IPv4Interface
  • ipaddress.IPv4Network
  • ipaddress.IPv6Address
  • ip address.IPv6 인터페이스
  • ipaddress.IPv6Network
  • enum.Enum
  • enum.IntEnum
  • decimal.Decimal
  • pathlib.Path
  • uuid.UUID
  • 바이트 크기

제한된 유형

다음을 통해 자신의 제한을 시행 할 수 있습니다.제한된 유형. 다음 예를 살펴 보겠습니다.

from pydantic import (
BaseModel,
NegativeInt,
PositiveInt,
conint,
conlist,
constr
)
class Model(BaseModel):
# minimum length of 2 and maximum length of 10
short_str: constr(min_length=2, max_length=10)
# regex
regex_str: constr(regex=r'^apple (pie|tart|sandwich)$')
# remove whitespace from string
strip_str: constr(strip_whitespace=True)

# value must be greater than 1000 and less than 1024
big_int: conint(gt=1000, lt=1024)

# value is multiple of 5
mod_int: conint(multiple_of=5)

# must be a positive integer
pos_int: PositiveInt

# must be a negative integer
neg_int: NegativeInt

# list of integers that contains 1 to 4 items
short_list: conlist(int, min_items=1, max_items=4)

엄격한 유형

검증 된 값이 해당 유형이거나 해당 유형의 하위 유형 인 경우에만 검증을 통과하는 엄격한 제한을 찾고 있다면 다음과 같은 엄격한 유형을 사용할 수 있습니다.

  • StrictStr
  • StrictInt
  • StrictFloat
  • StrictBool

다음 예는 적절한 시행 방법을 보여줍니다.StrictBool상속 된 클래스에서.

from pydantic import BaseModel, StrictBool,class StrictBoolModel(BaseModel):
strict_bool: StrictBool

문자열'그릇된'둘 중 하나만 허용하므로 ValidationError를 발생시킵니다.진실또는그릇된입력으로.

유효성 검사기

또한 다음을 사용하여 사용자 정의 유효성 검사기를 만들 수 있습니다.검증 인상속 된 클래스 내부의 데코레이터. 다음 예를 살펴 보겠습니다.신분증4 자리 숫자이고비밀번호 확인일치암호들.

from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, ValidationError, validator
class User(BaseModel):
id: int
username : str
password : str
confirm_password : str
alias = 'anonymous'
timestamp: Optional[datetime] = None
friends: List[int] = []
@validator('id')
def id_must_be_4_digits(cls, v):
if len(str(v)) != 4:
raise ValueError('must be 4 digits')
return v
@validator('confirm_password')
def passwords_match(cls, v, values, **kwargs):
if 'password' in values and v != values['password']:
raise ValueError('passwords do not match')
return v

3. 결론

오늘 배운 내용을 요약 해 보겠습니다.

데이터를 구문 분석하고 검증하는 데 도움이되는 Pydantic에 대한 자세한 설명부터 시작했습니다.

다음으로 가상 환경을 만들고 pip 또는 conda를 통해 Pydantic을 설치했습니다. 또한 사용 사례에 따라 세 가지 추가 종속성에 대한 지원도 포함됩니다.

설치가 완료되면 패키지에서 제공하는 기본 기능을 심도있게 살펴 보았습니다. 기본 구성 요소는 다음에서 상속되는 새 클래스를 만드는 것입니다.BaseModel.

Pydantic은 Python 표준 라이브러리에서 대부분의 일반적인 데이터 유형을 지원한다는 것을 배웠습니다. 우리는제한된 유형엄격한 유형사용자 지정 제한을 적용하는 데 도움이됩니다.

마지막으로, 당신은검증 인네 자리 입력 만 허용하는 데코레이터신분증, 그리고비밀번호 확인일치해야합니다암호들.

이 글을 읽어 주셔서 감사합니다. 다음 기사에서 다시 뵙기를 바랍니다!

The Beginner’s Guide to Pydantic

A Python package to parse and validate data

Aug 10 · 7 min read
Photo by Marc Babin on Unsplash

The topic for today is on data validation and settings management using Python type hinting. We are going to use a Python package called pydantic which enforces type hints at runtime. It provides user-friendly errors, allowing you to catch any invalid data. Based on the official documentation, Pydantic is

“… primarily a parsing library, not a validation library. Validation is a means to an end: building a model which conforms to the types and constraints provided.

In other words, pydantic guarantees the types and constraints of the output model, not the input data.”

There are three sections in this tutorial:

  1. Setup
  2. Implementation
  3. Conclusion

Let’s proceed to the next section and start installing the necessary modules.

1. Setup

It is highly recommended to create a virtual environment before you proceed with the installation.

Basic installation

Open up a terminal and run the following command to install pydantic

pip install pydantic

Upgrade existing package

If you already have an existing package and would like to upgrade it, kindly run the following command:

pip install -U pydantic

Anaconda

For Anaconda users, you can install it as follows:

conda install pydantic -c conda-forge

Optional dependencies

pydantic comes with the following optional dependencies based on your needs:

  • email-validator — Support for email validation.
  • typing-extensions — Support use of Literal prior to Python 3.8.
  • python-dotenv — Support for dotenv file with settings.

You can install them manually:

# install email-validator
pip install email-validator
# install typing-extensions
pip install typing_extensions
# install python-dotenv
pip install python-dotenv

or along with pydantic as follows:

# install email-validator
pip install pydantic[email]
# install typing-extensions
pip install pydantic[typing_extensions]
# install python-dotenv
pip install pydantic[dotenv]
# install all dependencies
pip install pydantic[email,typing_extensions,dotenv]

2. Implementation

In this section, we are going to explore some of the useful functionalities available in pydantic.

Defining an object in pydantic is as simple as creating a new class which inherits from theBaseModel. When you create a new object from the class, pydantic guarantees that the fields of the resultant model instance will conform to the field types defined on the model.

Import

Add the following import declaration at the top of your Python file.

from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel

User class

Declare a new class which inherits the BaseModel as follow:

class User(BaseModel):
id: int
username : str
password : str
confirm_password : str
alias = 'anonymous'
timestamp: Optional[datetime] = None
friends: List[int] = []

pydantic uses the built-in type hinting syntax to determine the data type of each variable. Let’s explore one by one what happens behind the scenes.

  • id — An integer variable represents an ID. Since the default value is not provided, this field is required and must be specified during object creation. Strings, bytes, or floats will be coerced to integer if possible; otherwise, an exception will be raised.
  • username — A string variable represents a username and is required.
  • password — A string variable represents a password and is required.
  • confirm_password — A string variable represents a confirmation password and is required. It will be used for data validation later on.
  • alias — A string variable represents an alias. It is not required and will be set to anonymous if it is not provided during object creation.
  • timestamp — A date/time field, which is not required. Default to None. pydantic will process either a unix timestamp int or a string representing the date/time.
  • friends — A list of integer inputs.

Object instantiation

The next step is to instantiate a new object from the User class.

data = {'id': '1234', 'username': 'wai foong', 'password': 'Password123', 'confirm_password': 'Password123', 'timestamp': '2020-08-03 10:30', 'friends': [1, '2', b'3']}user = User(**data)

You should get the following output when you print out the user variable. You can notice that id has been automatically converted to an integer, even though the input is a string. Likewise, bytes are automatically converted to integers, as shown by the friends field.

id=1234 username='wai foong' password='Password123' confirm_password='Password123' timestamp=datetime.datetime(2020, 8, 3, 10, 30) friends=[1, 2, 3] alias='anonymous'

Methods and attributes under BaseModel

Classes that inherit the BaseModel will have the following methods and attributes:

  • dict() — returns a dictionary of the model’s fields and values
  • json() — returns a JSON string representation dictionary
  • copy() — returns a deep copy of the model
  • parse_obj() — a utility for loading any object into a model with error handling if the object is not a dictionary
  • parse_raw() — a utility for loading strings of numerous formats
  • parse_field() — similar to parse_raw() but meant for files
  • from_orm() — loads data into a model from an arbitrary class
  • schema() — returns a dictionary representing the model as JSON schema
  • schema_json() — returns a JSON string representation of schema()
  • construct() — a class method for creating models without running validation
  • __fields_set__ — Set of names of fields which were set when the model instance was initialized
  • __fields__ — a dictionary of the model’s fields
  • __config__ — the configuration class for the model

Let’s change the input for id to a string as follows:

data = {'id': 'a random string', 'username': 'wai foong', 'password': 'Password123', 'confirm_password': 'Password123', 'timestamp': '2020-08-03 10:30', 'friends': [1, '2', b'3']}user = User(**data)

You should get the following error when you run the code.

value is not a valid integer (type=type_error.integer)

ValidationError

In order to get better details on the error, it is highly recommended to wrap it inside a try-catch block, as follows:

from pydantic import BaseModel, ValidationError# ... codes for User classdata = {'id': 'a random string', 'username': 'wai foong', 'password': 'Password123', 'confirm_password': 'Password123', 'timestamp': '2020-08-03 10:30', 'friends': [1, '2', b'3']}try:
user = User(**data)
except ValidationError as e:
print(e.json())

It will print out the following JSON, which indicates that the input for id is not a valid integer.

[
{
"loc": [
"id"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]

Field types

pydantic provides support for most of the common types from the Python standard library. The full list is as follows:

  • bool
  • int
  • float
  • str
  • bytes
  • list
  • tuple
  • dict
  • set
  • frozenset
  • datetime.date
  • datetime.time
  • datetime.datetime
  • datetime.timedelta
  • typing.Any
  • typing.TypeVar
  • typing.Union
  • typing.Optional
  • typing.List
  • typing.Tuple
  • typing.Dict
  • typing.Set
  • typing.FrozenSet
  • typing.Sequence
  • typing.Iterable
  • typing.Type
  • typing.Callable
  • typing.Pattern
  • ipaddress.IPv4Address
  • ipaddress.IPv4Interface
  • ipaddress.IPv4Network
  • ipaddress.IPv6Address
  • ipaddress.IPv6Interface
  • ipaddress.IPv6Network
  • enum.Enum
  • enum.IntEnum
  • decimal.Decimal
  • pathlib.Path
  • uuid.UUID
  • ByteSize

Constrained types

You can enforce your own restriction via the Constrained Types. Let’s have a look at the following example:

from pydantic import (
BaseModel,
NegativeInt,
PositiveInt,
conint,
conlist,
constr
)
class Model(BaseModel):
# minimum length of 2 and maximum length of 10
short_str: constr(min_length=2, max_length=10)
# regex
regex_str: constr(regex=r'^apple (pie|tart|sandwich)$')
# remove whitespace from string
strip_str: constr(strip_whitespace=True)

# value must be greater than 1000 and less than 1024
big_int: conint(gt=1000, lt=1024)

# value is multiple of 5
mod_int: conint(multiple_of=5)

# must be a positive integer
pos_int: PositiveInt

# must be a negative integer
neg_int: NegativeInt

# list of integers that contains 1 to 4 items
short_list: conlist(int, min_items=1, max_items=4)

Strict types

If you are looking for rigid restrictions which pass validation if and only if the validated value is of the respective type or is a subtype of that type, you can use the following strict types:

  • StrictStr
  • StrictInt
  • StrictFloat
  • StrictBool

The following example illustrates the proper way to enforce StrictBool in your inherited class.

from pydantic import BaseModel, StrictBool,class StrictBoolModel(BaseModel):
strict_bool: StrictBool

The string ‘False’ will raise ValidationError as it will only accept either True or False as input.

Validator

Furthermore, you can create your own custom validators using the validator decorator inside your inherited class. Let’s have a look at the following example which determine if the id is of four digits and whether the confirm_password matches the password field.

from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, ValidationError, validator
class User(BaseModel):
id: int
username : str
password : str
confirm_password : str
alias = 'anonymous'
timestamp: Optional[datetime] = None
friends: List[int] = []
@validator('id')
def id_must_be_4_digits(cls, v):
if len(str(v)) != 4:
raise ValueError('must be 4 digits')
return v
@validator('confirm_password')
def passwords_match(cls, v, values, **kwargs):
if 'password' in values and v != values['password']:
raise ValueError('passwords do not match')
return v

3. Conclusion

Let’s recap what we have learned today.

We started off with a detailed explanation on Pydantic which helps to parse and validate data.

Next, we created a virtual environment and installed Pydantic via pip or conda. It also includes support for three additional dependencies based on our use cases.

Once we were done with the installation, we explored in-depth the basic functionalities provided by the package. The basic building block is to create a new class which inherits from BaseModel.

We learned that Pydantic provides support for most of the common data types under Python standard library. We tested out both the Constrained Types and Strict Types which helps to enforce our own custom restrictions.

Lastly, you played around with the validator decorator to allow only four digits input for id, and the confirm_password must match the password field.

Thanks for reading this piece. Hope to see you again in the next article!

삶을 더 쉽게 만드는 파이썬의 7 가지 명령

IPython 및 Jupyter 노트북에 유용한 명령

Image for post
~의 사진그렉 라 코지의 위에Unsplash

파이썬이 1991 년에 처음 등장했을 때, 그것은 "자신의 위험에 처한"컴퓨팅 언어로 더 많이 인식되었습니다. 오늘날 이는 데이터 과학, 기계 학습 및 소프트웨어 개발을위한 주요 언어입니다.

Python이 인기있는 주요 이유는 다음과 같은 새로운 기능과 기술을 추가 할 때 유연성이 있기 때문입니다.마법의 명령.

그렇다면 Python에서 마술 명령은 정확히 무엇입니까?

매직 명령은 일상적인 작업을 용이하게하도록 설계된 일반적인 Python 구문보다 향상된 기능 또는 바로 가기입니다.

이러한 특수 명령을 사용하면IPython외부 스크립트를 실행하거나 코드 조각의 실행 시간을 계산하는 등 표준 데이터 분석의 다양한 일반적인 문제를 해결합니다.

이 튜토리얼에서는 매우 유용한 몇 가지 주문을 알려 드리겠습니다. 이것들은 더 나은 프로그래밍 마법사가되는 데 도움이 될 것입니다.

이 모든 명령은 사전에 테스트되었습니다.Jupyter 노트북달리는Python 버전 3.7.4. 이 명령은 IDE의 모든 IPython 셸에서 완벽하게 실행되어야합니다.스파이더,파이 참

매직 명령은 두 가지 형태로 제공됩니다.

  • 라인 매직— 단일로 표시접두사이며 한 줄의 입력에서 작동합니다.
  • 세포 마법— 이중으로 표시접두사이며 전체 셀 또는 여러 줄의 입력에서 작동합니다.

가장 인기있는 몇 가지 마법 명령을 살펴 보겠습니다.

외부 스크립트 실행

새로운 프로젝트를 진행하고 있다고 가정합니다.Jupyter, 이전에 작성한 스크립트를 사용하려고합니다. 전체 코드를 Jupyter 셀에 복사하는 대신 Python 마법을 사용할 수 있습니다.

모든 스크립트는 다음을 사용하여 IPython 세션의 환경 내에서 실행할 수 있습니다.명령.

다음과 같은 파일이 있다고 가정합니다.다음 코드로 :

이를 실행하기 위해 다음을 사용합니다.

%run test_script.py

스크립트는 정의 된 가져 오기 또는 변수가없는 빈 네임 스페이스에서 실행됩니다.

동작은 다음을 사용하여 명령 줄에서 프로그램을 실행하는 것과 동일합니다..

참고 : 다음을 사용하여 이미 정의 된 변수에 대한 액세스를 제공 할 수 있습니다..

실행 된 스크립트에 정의 된 모든 변수는 이제 IPython 셸에서 액세스 할 수 있습니다.

예를 들어 외부 스크립트에 정의 된 함수를 재사용하는 방법을 참조하십시오.

Image for post
출처 : 저자

필요한 경우 인수를 전달할 수도 있습니다. 여기서는 명령과 함께 단일 정수 인수를 전달합니다.

%run python_script.py 10`

에 대해 더 읽을 수 있습니다여기에서 외부 스크립트 실행.

외부 스크립트를 셀로 가져 오기 /보기

다음을 사용하여 외부 스크립트를 실행할 수 있습니다.명령. 그러나 스크립트를 노트북 셀에 복사해야하는 상황이 있습니다.

걱정하지 마세요. Ctrl-C 및 Ctrl-V로 돌아갈 필요가 없습니다.

~의 사진엘리 존슨의 위에Unsplash

그만큼매직 함수를 사용하면 스크립트를 코드 셀로 직접 가져올 수 있습니다.

%load test_script.py

위의 문장을 입력하고 실행을 누르십시오. 여기에서 마법을 직접 확인하십시오.

Image for post
출처 : 저자

비슷한명령, 우리는. 노트북을 떠나지 않고도 파일의 내용을 볼 수 있습니다.

%pycat test_script.py

외부 파일의 모든 내용을 출력으로 표시합니다.

Image for post
출처 : 저자

에 대해 더 읽을 수 있습니다여기에 외부 스크립트 가져 오기.

노트북 셀을 외부 스크립트로 내보내기

데이터 과학자로서 저는 종종Jupyter 노트북. 그러나 프로덕션과 관련하여 코드는스크립트 파일.

여기,마법이 유용합니다.셀 내용 전체를 외부 파일로 내 보냅니다.

구경하다:

이중 퍼센트 () 여기에 서명하십시오.세포 마법입니다.

기존 파일에 코드를 추가 할 수도 있습니다.

에 대해 더 읽을 수 있습니다여기에 셀 내보내기.

코드 실행 시간

Python 표현식을 실행하기 위해 IPython 환경에 필요한 시간을 계산합니다.

Image for post
~의 사진아론 비주얼의 위에Unsplash

이것을 사용하여 목록 이해력의 성능을고리.

처음 1,000 개의 자연수의 제곱을 포함하는 목록을 만들 것입니다.

Image for post
출처 : 저자

표현식의 여러 실행을 수행합니다. 평균적으로 여러 번 실행되므로 결과가 더 안정적입니다.

우리는 또한() 코드 블록의 경우.

다음을 사용하여 동일한 목록을 만들어 보겠습니다.고리:

Image for post

이 시나리오에서 목록 이해는 동등한 것보다 약 10 % 더 빠릅니다.고리.

에 대해 더 읽을 수 있습니다여기에서 코드 시간 실행.

네임 스페이스에 변수 나열

네임 스페이스에 정의 된 모든 변수를 나열해야하는 경우 사용할 수있는 세 가지 명령이 있습니다.

  • : 최소한의 형식으로 모든 대화 형 변수를 인쇄합니다.
  • : 모든 변수를 정렬 된 목록으로 반환합니다.
  • : 처럼, 그러나 각 변수에 대한 추가 정보를 제공합니다.

예를 들면 다음과 같습니다.

위의 코드는 네임 스페이스의 모든 사용자 정의 변수를 표시합니다. 특정 데이터 유형을 인수로 전달하여 표시 할 수 있습니다.

%who str# Output
# name

매우 유사하게 작동합니다. 유일한 차이점은 출력이 목록 형식이라는 것입니다.

%who_ls#Output:
# ['age', 'name', 'roll_number']

변수에 대한 자세한 정보를 제공합니다.

Image for post
출처 : 저자

에 대해 더 읽을 수 있습니다여기에 변수 나열.

HTML 스크립트 실행

코드에 간단한 UI 요소를 제공해야하는 경우 IPython에서도 HTML 및 JavaScript 코드를 실행할 수 있습니다.

셀에 HTML 코드를 작성할 수 있습니다. JavaScript의 경우.

다음은 HTML로 간단한 표를 렌더링하는 예입니다.

셀은 HTML 편집기 역할을합니다. 코드가 실행되면 HTML 출력이 수신됩니다.

Image for post
출처 : 저자

에 대해 더 읽을 수 있습니다여기서 HTML 스크립트 실행.

환경 변수 작업

그만큼magic 명령을 사용하면 시스템 환경 변수에 액세스하고 조작 할 수 있습니다.

Image for post
~의 사진아이작 스미스의 위에Unsplash

다음 중 하나를 수행 할 수 있습니다.

  • — 모든 환경 변수 나열
  • — 변수 값 가져 오기
  • — 변수 값 설정

매개 변수없이모든 환경 변수를 나열합니다.

Image for post
출처 : 저자

특정 변수의 값을 반환하는 매개 변수를 추가합니다.

Image for post
출처 : 저자

에 대해 더 읽을 수 있습니다여기에서 환경 변수 작업.

결론

다음을 사용하여 몇 가지 예와 함께 사용 가능한 매직 함수에 대한 일반적인 설명을 볼 수 있습니다.

%magic

특정 마법 기능에 대한 정보도 얻을 수 있습니다. 예를 들어 문서를 읽으려면마법은 다음을 입력하십시오.

Image for post
출처 : 저자

자신 만의 매직 함수를 정의하려면 다음을 읽어야합니다.더 많은 IPython 리소스.

그래서 여기에 나의 소중한 파이썬 마법 명령이 있습니다. 아래 댓글에서 가장 좋아하는 것을 알려주십시오.

이 튜토리얼이 흥미롭고 유용하기를 바랍니다.

7 Commands in Python to Make Your Life Easier

Useful commands for IPython and Jupyter Notebooks

Image for post
Photo by Greg Rakozy on Unsplash

When Python first appeared in 1991, it was seen more as an “at your own risk” computing language. Today it is the predominant language for data science, machine learning, and software development.

A key reason behind Python’s popularity is its flexibility when it comes to adding new features and technologies like magic commands.

So, what exactly is a magic command in Python?

Magic commands are enhancements or shortcuts over the usual Python syntax designed to facilitate routine tasks.

These special commands enable us to easily control the behavior of the IPython system and solve various common problems in standard data analysis, for example, running an external script or calculating the execution time of a piece of code.

In this tutorial, I will teach you some very useful spells. These will help you to become better programming wizards.

All these commands were tested beforehand on a Jupyter Notebook running Python version 3.7.4. These commands should run perfectly in any IPython shell on your IDE, like Spyder, Pycharm, etc.

Magic commands come in two different forms:

  • Line magic — is denoted by a single prefix and operates on a single line of input
  • Cell magic — is denoted by a double prefix and operates on the entire cell or multiple lines of input.

Let’s look at some of the most popular magic commands.

Run an External Script

Suppose you are working on a new project on Jupyter, and you wish to use a script that you wrote earlier. Rather than copying the entire code into a Jupyter cell, you can use some Python magic.

Any script can be run inside the environment of our IPython session using the command.

Suppose I have a file called with the following code:

To run it, we use:

%run test_script.py

The script will run in an empty namespace with no imports or variables defined.

The behavior is identical to running the program on a command line using .

Note: You can provide access to already defined variables using .

All of the variables defined in the executed script are now accessible in the IPython shell.

For example, see how I reuse a function defined in the external script:

Image for post
Source: Author

If needed, we can also pass arguments. Here, we pass a single integer argument along with our command.

%run python_script.py 10`

You can read more about running an external script here.

Import/View an External Script Into a Cell

We can run an external script using the command. But, there are situations when we must copy the script into a notebook cell.

Don’t worry, you don’t need to go back to Ctrl-C and Ctrl-V.

Photo by Elly Johnson on Unsplash

The magic function allows us to import a script directly into a code cell.

%load test_script.py

Just type the above statement and press run. Here, see the magic yourself:

Image for post
Source: Author

Similar to the command, we have . It allows us to view the content of any file without leaving our notebook.

%pycat test_script.py

displays all the content of the external file as its output.

Image for post
Source: Author

You can read more about importing an external script here.

Export a Notebook Cell as an External Script

As a data scientist, I often end up coding in a Jupyter notebook. But when it comes to production, the code needs to be in a script file.

Here, the magic comes in handy. exports the entirety of a cell’s content to an external file.

Take a look:

Notice the double percent() sign here, as is a cell magic.

We can also append code to an existing file.

You can read more about exporting a cell here.

Code Execution Time

calculates the time required by the IPython environment to execute a Python expression.

Image for post
Photo by Aron Visuals on Unsplash

Let’s use this to compare the performance of list comprehension with a loop.

We will create a list that contains the squares of the first 1,000 natural numbers.

Image for post
Source: Author

performs multiple runs of the expression. As we receive an average of several executions, the results are more reliable.

We also have a cell version for () for a code block.

Let’s create the same list using a loop:

Image for post

In this scenario, list comprehension is about 10% faster than an equivalent loop.

You can read more about code time execution here.

List Variables in the Namespace

If we need to list all the variables defined in the namespace, we have three commands at our disposal.

  • : Print all the interactive variables, with minimal formatting
  • : Returns all the variables as a sorted list
  • : Like , but gives some extra information about each variable

Here’s an example:

The above code displays all the user-defined variables in the namespace. We can display specific data types by passing them as arguments.

%who str# Output
# name

works very similarly. The only difference is that the output is in the form of a list.

%who_ls#Output:
# ['age', 'name', 'roll_number']

provides detailed information about the variables.

Image for post
Source: Author

You can read more about listing variables here.

Execute HTML Script

If you need to provide some simple UI elements to your code, you can execute HTML and JavaScript code in IPython as well.

allows us to write HTML code in the cell. For JavaScript, use .

Here’s an example that will render a simple table in HTML:

The cell acts as an HTML editor. Once the code is run, you receive the HTML output.

Image for post
Source: Author

You can read more about executing HTML script here.

Work With Environment Variables

The magic command allows you to access and manipulate system environment variables.

Image for post
Photo by Isaac Smith on Unsplash

You can either:

  • — List all the environment variables
  • — Get value for variable
  • — Set value for variable

Without any parameter, will list down all the environment variables.

Image for post
Source: Author

We add a parameter to return the value of a specific variable.

Image for post
Source: Author

You can read more about working with environment variables here.

Conclusion

You can see a general description of available magic functions, along with some examples, using:

%magic

We can also get information on a specific magic function. So, for example, to read the documentation of the magic simply type this:

Image for post
Source: Author

If you wish to define your own magic functions, you should read this: More IPython Resources.

So here were some of my treasured Python magic commands. Let me know your favorite ones in the comments below.

I hope you found this tutorial interesting and useful.

Python을 첫 번째 프로그래밍 언어로 선택하지 마십시오.

9 월 7 일 · 4최소 읽기
Python programming language
~의 사진샤 하닷 라만의 위에Unsplash

파이썬은 21 세기 가장 인기있는 프로그래밍 언어 중 하나입니다. 다음을 위해 사용되는 범용 언어입니다.웹 개발, 인공 지능, 기계 학습, 데이터 과학, 모바일 애플리케이션 개발 및 일부 비디오 게임.

오늘날 세계의 모든 최신 기술 트렌드는 직접 또는 간접적으로 Python 언어를 사용하고 있습니다. 이것이 초보자들이 그 언어를 배우고 싶어하는 가장 일반적인 이유입니다.

Python — 프로그래밍 핫샷!

파이썬은 뜨거운 추세입니다. 사람들은 일반적으로 소프트웨어 산업의 추세를 따릅니다. 나는 파이썬이 좋은 프로그래밍 언어가 아니라고 말하는 것은 아니지만 일종의 과장된 것입니다.

Python의 가장 좋은 점은 더 적은 코드로 작업을 수행 할 수있는 단순성과 능력입니다. Python에서 코드 줄 수의 거의 절반을 사용하여 다른 언어로 10 ~ 20 줄의 코드 작업을 수행 할 수 있습니다.

머신 러닝과 AI는 다른 프로그래밍 언어로 수행 할 수 있지만 여전히 파이썬이 가장 좋습니다.

Python의 문제점

파이썬은 너무 간단합니다. 객체 지향 프로그래밍의 중요한 요소가 부족합니다. 숙련 된 프로그래머는 OOP 개념에 대한 명령을 사용하면서 특정 요구에 맞게 Python을 배웁니다.

초보자는 소프트웨어 산업에서 무리의 사고 방식을 따르기 전에 두 번 생각해야 할 수도 있습니다. 초보자가 첫 프로그래밍 언어로 Python을 선택하지 않아야하는 이유는 많이 있습니다.

1. Python 객체 생성에는 유형이 필요하지 않습니다.

어떤 수준에서는 코딩이 더 쉬워집니다. 그러나 제 생각에는 새로운 프로그래머에게는 끔찍한 일입니다. 그들은 그들이 만드는 모든 객체의 유형을 알고 있어야하며 이것은 파이썬 언어에서 훨씬 더 어려워집니다.

2. 파이썬에는 개인 클래스 멤버가 없습니다.

OOP 개념의 핵심은캡슐화정보 숨기기. 클래스에는 개인 멤버가 있어야합니다. 하지만 파이썬에서는 거의 불가능합니다. (Python의 의사 비공개 멤버 인‘__foo’는 의미가 없습니다.)

3. Python의 멤버 함수는 순전히 가상입니다.

Python에서는 인터페이스가 필요하지 않습니다. 인터페이스는 새로운 프로그래머가 캡슐화 개념을 이해하는 데 중요합니다. 그러나 Python에서는 인터페이스 작성이 권장되지 않습니다 (언어 자체).

4. 거의 모든 것을위한 라이브러리

137,000 개가 넘습니다Python 라이브러리오늘. 라이브러리는 코드를 처음부터 작성할 필요가없는 유용한 함수 세트입니다. 코딩을 처음 접하는 사람에게는 학습 곡선이 크게 줄어들 기 때문에 좋은 방법이 아닙니다.

5. 스레드 문제

원래 (또는 공식) Python 구현,CPython, 전역 통역 잠금이 있습니다. 따라서 실제 동시 스레드가 없습니다. 또한 Python에서 코드의 동시성 부분은 C ++ 또는 Java만큼 강력하지 않습니다.

6. 속도는 환상

우리가 알고 있듯이 Python은 C 언어로 작성되었으므로 대부분의 라이브러리도 마찬가지입니다. 일반적으로 프로그래밍 언어의 라이브러리는 동일한 언어로 작성되지만 Python의 경우 대부분의 라이브러리가 C 및 C ++로 작성됩니다.

7. 중괄호 대신 들여 쓰기

많은 개발자가 Python의 들여 쓰기를 좋아합니다. 그러나 중괄호가있는 코드는 초보자에게 더 좋습니다. 훨씬 더 명확한보기를 제공하고 코드 블록을 완전히 구분하므로 쉽게 이해할 수 있습니다.

def say_hello():
print("Tab") # I use tab to make indentation here
print("Space") # I use space to make indentation here
Do you see the differences between tabs and spaces?

8. 런타임 오류 처리

파이썬은동적으로 입력언어. 더 많은 테스트가 필요하며 동적 특성으로 인해 런타임에만 표시되는 오류가 있습니다. 이것은 초보자에게 정말 실망스럽고 실망 스러울 수 있습니다.

9. 당신의 관심은 무엇입니까

모바일 애플리케이션이나 게임 개발자가되는 데 관심이 있다면 Python이 적합한 기술이 아닐 수 있습니다!

또한 Python은 동적 및 후기 바인딩 특성으로 인해 메모리 효율적이지 않습니다. 따라서 애플리케이션이 속도와 메모리 효율성을 요구한다면 대안을 찾아야합니다.

10. 배포 및 디버깅 문제

Python의 주요 문제 중 하나는 애플리케이션이 성장하기 시작하고 배포가 문제가되며 모든 문제에 대해 프로덕션 코드를 디버그하기가 매우 어렵다는 것입니다.

결론

Python을 첫 번째 언어로 선택하면 매우 나쁜 코딩 스타일 (많은 공용 멤버 변수, 인터페이스 부족 등)을 형성 할 수 있으며 결국 객체 지향 프로그래밍에 대한 이해가 부족할 수 있습니다.

OOP 개념을 더 잘 이해하려면 C ++ 또는 Java로 시작하는 것이 좋습니다.

진실은 모든 것을위한 완벽한 프로그래밍 언어는 결코있을 수 없다는 것입니다.

파이썬은 좋은 프로그래밍 언어이지만 적어도 하나의 객체 지향 프로그래밍 언어를 명령 한 후에 배우는 것을 고려해야합니다. 또한 기계 학습, AI 또는 데이터 과학 분야의 경력을 구체적으로 찾고 있다면 배우십시오.

저는 Shubham Pathania입니다. 저는 금융 분야에서 일하는 .NET 개발자입니다. 저는 C #이 사용하기에 훌륭한 언어라고 생각하고 훌륭한 에코 시스템의 지원을받습니다. 저는 복잡한 문제를 해결하는 것을 좋아하고 제가 사용하는 기술에 대해 계속 이야기하고 싶습니다.

이 기사가 도움이되거나 생각을 자극했다면 댓글을 남기고 연결해 봅시다.LinkedIn!

다음은 즐길 수있는 몇 가지 다른 기사입니다.

Don’t Choose Python as Your First Programming Language

Sep 7 · 4 min read

Python is one of the most popular programming languages of the 21st Century. It is a general-purpose language used for Web Development, Artificial Intelligence, Machine Learning, Data Science, Mobile Application development, and some Video Games.

All the latest technology trends in today’s world are directly or indirectly using Python language. That is the most common reason why beginners want to learn that language.

Python — Programming Hotshot!

Python is a hot trend. People usually run after trends in Software Industry. I am not suggesting that Python is not a good programming language but it is kind of hyped.

The best thing about Python is its simplicity and ability to do tasks with less code. You can perform a task of 10–20 lines of code in some other language with almost half the number of lines of code in Python.

Even though Machine Learning and AI can be done in other programming languages, still, python is best to do so.

What’s wrong with Python

Python is too simple. It lacks Important elements of object-oriented programming. An experienced programmer will learn Python for specific needs while having command over the OOPs concept.

A beginner might have to think twice before following the herd mentality in the software industry. There are plenty of reasons why a beginner should not choose Python as their first programming language —

1. Python object creation does not need a Type

To some level, it makes coding easier. But, in my opinion, it is terrible for new programmers. They should be aware of the types of whatever objects they create, and this becomes much harder in Python language.

2. Python lacks private class members

The key to the OOPs concept is Encapsulation and Information hiding. A class should have its private members. But in Python, this is nearly impossible. (The pseudo-private members in Python, ‘__foo’ don’t make much sense.)

3. Member functions in Python are purely virtual

In Python, there is no need for Interfaces. Interfaces are important for new programmers, to understand the notion of encapsulation. But in Python, writing interfaces is just not encouraged (By the language itself).

4. Library for almost everything

There are over 137,000 Python libraries present today. Libraries are a set of useful functions that eliminate the need for writing codes from scratch. This is not a good practice for someone who is new to coding as this will drastically reduce their learning curve.

5. Issues with Thread

The original (or official) Python implementation, CPython, has a global interpretation lock. So, there are no real concurrent threads. Furthermore, the concurrency part of code in Python is just not as strong as C++ or Java.

6. Speed is an illusion

As we know Python is written in C language, so are most of its libraries. Usually, the libraries of a programming language are written in the same language but in the case of Python, most of the libraries are written in C and C++.

7. Indentation instead of curly braces

Many developers love Python’s indentation. However, code with curly braces would be better for beginners. It provides a much clearer view and also completely differentiates the blocks of code, which is easily understandable for them.

def say_hello():
print("Tab") # I use tab to make indentation here
print("Space") # I use space to make indentation here
Do you see the differences between tabs and spaces?

8. Dealing with Runtime Errors

Python is a dynamically typed language. It requires more testing and has errors that only show up at runtime due to dynamic nature. This could be really frustrating and discouraging for beginners.

9. What’s your Interest

If you are interested in becoming a mobile application or game developer then Python might not be the right technology for you!

Python is also not memory-efficient due to its dynamic and late-binding nature. So if your application demands speed and memory efficiency then you have to look for alternatives.

10. Deployment and Debugging challenges

One of the main issues with Python is when applications start growing, deployment becomes an issue, and also it is very difficult to debug production code for any issues.

Conclusion

If you choose Python as your first language to study, you might form some very bad coding styles (lots of public member variables, lack of interfaces, etc), and you might end up with a poor understanding of Object-Oriented Programming.

It is better to start with C++ or Java to develop a better understanding of the OOPs concept.

The truth is, there can never be a perfect programming language for everything.

Python is a good programming language, but you should consider learning it after commanding at least one Object-oriented programming language. Also, learn it if you are specifically seeking a career in Machine Learning, AI, or Data Science.

I’m Shubham Pathania. I’m a .NET developer working in the finance domain. I find C# a great language to use, and it’s also backed by a great ecosystem. I love solving complex problems and want to continue talking about the tech I use.

If you found this article helpful or thought-provoking, leave a comment, and let’s connect over LinkedIn!

Here are some other articles you may enjoy:

데이터 과학 용 Visual Studio Code — 고급 사용자 가이드

전형적인 IDE?

Visual Studio Code
출처:Wikipedia의 Visual Studio 코드

미디엄icrosoft의 Visual Studio Code는 개발자를위한 최고의 IDE 중 하나입니다. 데이터 과학자도 마찬가지입니다. VS Code에는 뛰어난 사용자 경험을 제공하는 다양한 도구와 확장이 있습니다.

설정

설치VS 코드 용 Python신장

R의 경우 설치아르 자형신장

환경

종종 기본 설치에서 사용할 수없는 패키지와 모듈이 필요합니다. 일부 라이브러리 또는 응용 프로그램은 사용할 특정 버전의 라이브러리를 지정합니다. 이러한 경우 가상 환경이 유용합니다.

Anaconda를 사용하여 Python 배포를 사용하여 Python을 설정할 수 있습니다.

환경을 관리하려면 VS Code에서 명령 팔레트 ()에서 원하는 환경을 선택할 수 있습니다.⇧⌘P) > Python : 인터프리터 선택.

Image for post
Python : 인터프리터 선택
Image for post
Python 환경 선택

작업 공간

작업 공간 설정은 작업 공간 내에 저장되며 작업 공간이 열린 경우에만 적용됩니다. 전역 사용자 설정을 재정의합니다. 이러한 방식으로 각 데이터 과학 작업 영역을 사용자 지정 구성 할 수 있습니다.

Jupyter 노트북

Jupyter

그만큼Jupyter 노트북라이브 코드, 방정식, 시각화 및 설명 텍스트가 포함 된 문서를 만들고 공유 할 수있는 오픈 소스 웹 애플리케이션입니다.

REPL (Read-Evaluate-Print-Loop) 쉘을 사용하여 IPython의 후속 제품으로 개발 된 Jupyter 노트북은 데이터 과학을위한 컴퓨팅 노트북입니다.

Jupyter 확장은 현재 유지 관리되지 않으며 Microsoft의 Python 플러그인에는 공식적으로 Jupyter 노트북에 대한 기본 지원이 포함됩니다.

Jupyter 설치

다음을 사용하여 작업 공간에 Jupyter를 설치합니다.pip 설치 jupyter

새 Jupyter 노트북을 만들려면 명령 팔레트 (⇧⌘P) > 새 빈 Jupyter 노트북을 만듭니다.

Image for post
새 Jupyter 노트북 열기

Jupyter 서버는 로컬로 설정되고 작업 공간 설정에 따라 Python 커널이 선택됩니다.

Image for post
Jupyter 노트북 툴바

확장

확장은 개발자를위한 Visual Studio Code 환경의 필수적인 부분입니다. 시각 효과에서 다른 서비스와의 통합에 이르기까지 다양합니다. 생산성을 높이기 위해 원하는만큼 인터페이스를 수정할 수 있습니다. 예를 들어, —Bracket Pair Colorizer는 색상이있는 하나의 누락되거나 추가 된 브래킷을 찾는 데 도움이되며, 후행 공백은 Python에서 정말 도움이되는 외부 공간을 찾는 데 도움이 될 수 있습니다.

Visual Studio Code에 대한 경험을 향상시킬 수있는 확장 목록은 다음 중간 게시물이 정말 도움이된다는 것을 알았습니다.

확장 기능 중 일부는 다음과 같습니다.

  • 후행 공백
  • 브래킷 매칭
  • GitLens
  • 숭고한 텍스트 키맵
  • Intellisense

통합 터미널

Image for post
통합 터미널

Visual Studio에는 기본적으로 루트 공간에서 시작하는 통합 터미널이 있습니다.

터미널을 열려면 :

  • 사용 (⌃`) 백틱 문자가있는 키보드 단축키.
  • Use the View > Terminal menu command.
  • 명령 팔레트 (⇧⌘P)보기 : 통합 터미널 전환 명령을 사용합니다.

여러 터미널 관리

터미널 패널의 오른쪽 상단에있는 더하기 아이콘을 클릭하거나 (⌃⇧`) 명령.

분할 터미널

()를 트리거하여 터미널을 분할 할 수도 있습니다.⌘ \) 명령 또는 오른쪽 클릭 상황에 맞는 메뉴를 통해.

버전 관리

Git
출처:열어 젖히다

버전 제어는 모든 개발자 또는 프로젝트에 필수적이며 팀간에 서로 다른 모듈 및 버전 작업을 용이하게합니다. 소스 코드의 변경 사항을 추적하기위한 분산 버전 제어 시스템 인 Git이 Visual Studio Code에 깔끔하게 통합되었습니다.

Git in VS Code
Git 기록 (git log)

VS Code에서 Git을 시작하려면 공식 확장 이름을 다운로드하여 설치하십시오.GitHub 풀 요청 및 문제. 또는 확장을 설치할 수 있습니다.GitLens. GitLens는 Git blame 주석 및 코드 렌즈를 통해 코드 작성자를 시각화하고 Git 리포지토리를 탐색 및 탐색하는 데 도움이됩니다.

나를 따라와LinkedInGitHub또는 내 웹 사이트를 방문하십시오.rohithsajja.me

Visual Studio Code for Data Science — the Power User’s guide

The quintessential IDE?

Visual Studio Code
Source: Visual Studio Code on Wikipedia

Microsoft’s Visual Studio Code is arguably one of the best IDEs for developers. The same is true for Data Scientists. There are numerous tools and extensions in the VS Code that enable users with great user experience.

Setup

Install the Python for VS Code extension

For R, install R extension

Environments

Often, you will require packages and modules that are not available by default installation. Some libraries or applications specify a particular version of a library to be used. Virtual environments are useful in these cases.

You can setup Python using Python distributions using Anaconda.

To manage your environment, in VS Code, you can select an environment of your choice from the Command Palette ( ⇧⌘P ) > Python: Select Interpreter.

Image for post
Python: Select Interpreter
Image for post
Selecting a Python environment

Workspaces

Workspace Settings are stored inside your workspace and only apply when the workspace is opened. They override the global user settings. This way each of the Data Science workspaces can be custom configured.

Jupyter Notebooks

Jupyter

The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text.

Developed as a successor to IPython with REPL (Read-Evaluate-Print-Loop) shell, Jupyter Notebooks are the computational notebook of choice for Data Science.

The Jupyter extension is not being maintained currently, and the Python plugin from Microsoft officially includes native support for Jupyter Notebooks.

Install Jupyter

Install Jupyter in your workspace using pip install jupyter

To create a new Jupyter notebook — use the Command Palette ( ⇧⌘P ) > Create New Blank Jupyter Notebook.

Image for post
Open a new Jupyter Notebook

The Jupyter server will be set to local, and a python kernel is selected based on your workspace settings.

Image for post
Jupyter Notebook toolbar

Extensions

Extensions are an integral part of the Visual Studio Code experience for developers. They range from visual effects to integration with other services. You can modify your interface as much as you wish to enhance productivity, for example —Bracket Pair Colorizer helps you find that one missing or extra bracket with colors, or Trailing spaces can help you find the extraneous spaces, which is really helpful in python.

For a list of extensions that can improve your experience on Visual Studio Code, I found the following medium post really helpful.

Some of the extensions include:

  • Trailing spaces
  • Bracket Matching
  • GitLens
  • Sublime Text KeyMap
  • Intellisense

Integrated terminal

Image for post
Integrated Terminal

Visual Studio has an integrated terminal, that starts at the root space by default.

To open the terminal:

  • Use the ( ⌃` ) keyboard shortcut with the backtick character.
  • Use the View > Terminal menu command.
  • From the Command Palette ( ⇧⌘P ), use the View: Toggle Integrated Terminal command.

Managing multiple terminals

Terminal instances can be added by clicking the plus icon on the top-right of the TERMINAL panel or by triggering the ( ⌃⇧` ) command.

Split terminals

You can also split the terminal by triggering the ( ⌘\ ) command or via the right-click context menu.

Version Control

Git
Source: unDraw

Version control is essential for any developer or project, helping facilitate working on different modules and versions by across teams. Git, the distributed version control system for tracking changes in your source code is neatly integrated into Visual Studio Code.

Git in VS Code
Git History (git log)

To get started with Git on VS Code, download and install the official extension names — GitHub Pull Requests and Issues. Or you can install the extension GitLens. GitLens helps you to visualize code authorship via Git blame annotations and code lens, and navigate and explore Git repositories.

Follow me on LinkedIn and GitHub, or visit my website at rohithsajja.me

Python에서 3 개의 다른 "Else"절을 사용하는 방법 배우기

잘 알려지지 않은 Python의 기능

7 월 24 일 · 5최소 읽기
Image for post
~의 사진톨가 울칸의 위에Unsplash

소개

"for"문

"for"루프의 기본 형식
"For… else"문

"while"문

"While"진술
"While… else"진술

"시도"진술

"try… except"진술의 기본 형식
"Try… except… else"문

결론

Learn to Use 3 Other “Else” Clauses in Python

Some lesser-known features of Python

Jul 24 · 5 min read
Image for post
Photo by Tolga Ulkan on Unsplash

Introduction

The “for” Statement

Basic Form of “for” Loop
“For…else” Statement

The “while” Statement

“While” Statement
“While…else” Statement

The “try” Statement

Basic Form of the “try…except” Statement
“Try…except…else” Statement

Conclusions

+ Recent posts