나 역시 파이써닉한 코드 << 가 Ultimate goal인 많은 사람들 중 하나인데
그러면서도 파이써닉한 코드가 정확히 무엇인지 설명하기는 어려운 것이 사실이었다.
snake_case
사용=
기준으로 앞 뒤 한 칸씩 띄어주기. 단, 괄호 안에 파라미터를 넣는 경우에는 빈칸이 Xa = 1000
b = 10
a, b = b, a
print(a,b)
>>> 10, 1000
pythonic한 코드에 관련된 글 몇 개를 읽었는데, 사실상 우리 회사에서 사용하고 있는 코딩 컨벤션이 파이써닉한 코드를 만들기 위한 모든 노력이었다는 것을 깨달았다. (넘 당연한 이야기인가..허허)
def practice():
arr = [[0 for _ in range(5)] for _ in range(5)]
print(arr)
practice()
>>> [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
The generator yields one item at a time and generates item only when in demand. Whereas, in a list comprehension, Python reserves memory for the whole list. Thus we can say that the generator expressions are memory efficient than the lists.
# import getsizeof from sys module
from sys import getsizeof
comp = [i for i in range(10000)]
gen = (i for i in range(10000))
#gives size for list comprehension
x = getsizeof(comp)
print("x = ", x)
#gives size for generator expression
y = getsizeof(gen)
print("y = ", y)
>>>
x = 87624
y = 88
There is a remarkable difference in the execution time. Generator expressions are faster than list comprehension and hence time efficient.
#List Comprehension:
import timeit
print(timeit.timeit('''list_com = [i for i in range(100) if i % 2 == 0]''', number=1000000))
>>> 8.118047142050102
#Generator Expression:
import timeit
print(timeit.timeit('''gen_exp = (i for i in range(100) if i % 2 == 0)''', number=1000000))
>>> 0.7548244756850693
위에서 작성한 코드는 range(100), if % 2 == 0
에서 100과 2부분을 바꿀 수 없다는 단점이 있다. (재사용성 및 범용성 낮을 저)
하지만 람다식과 함께라면 재사용성 및 범용성이 뛰어난 코드로 변모할 수 있다.
ge = lambda limit, int: (i for i in range(1, limit + 1) if i % int == 0)
Reference:
https://www.geeksforgeeks.org/python-list-comprehensions-vs-generator-expressions/
간지를 위해 빔을 사용하고 싶었지만 간지보다 실력, 작업 속도를 맞추기 위해 VS code에 정착한 상황이다. 조금 슬픈 마음이 들지만 어쩔 수 없다. 난 실용성을 (지나치게) 중시하는 ESTJ....
여튼 줄번호 이동을 위한 vs code 단축키는 command + G 후 줄 번호
이다.
django에는 다음과 같은 명령어가 있다.
python manage.py makemigrations
python manage.py migrate
python manage.py showmigrations
파이썬 프레임워크 django로 처음 개발을 시작한 나는 이 명령어들을 익히어 실제 개발에 사용하고 있(는 정도가 아니라 없음 못함)기 때문에, 당연히 장고단 내의 마이그레이션의 의미만 생각해봤다. 그러나 일반적인 마이그레이션의 정의는 다음과 같았다.
A validator is a callable that takes a value and raises a ValidationError if it doesn’t meet some criteria. Validators can be useful for re-using validation logic between different types of fields.
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
A classmethod that normalizes email addresses by lowercasing the domain portion of the email address.
django > contrib > auth > models > BaseUserManager
The rsplit() method splits a string into a list, starting from the right.
If no "max" is specified, this method will return the same as the split() method.
Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
split()
는 앞에서부터 delimiter를 기준으로 스트링을 나누지만rsplit()
는 뒤에서부터 스트링을 나눔
str = "//SF"
result = str1.rsplit('/')
print(result)
# 실행 결과:
['', '', 'SF']
하지만 분할 횟수를 넣어주면 어떨까?
str1 = "//SF"
result = str1.rsplit('/', **1**)
print(result)
# 실행 결과:
['/', 'SF']