Python 에러 핸들링 방식: Printing vs Logging

# option A
try:
    do_something_that_might_error()
except Exception as error:
    traceback.print_exc()

# option B
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

try:
    do_something_that_might_error()
except Exception as error:
    logger.exception(error)

파이썬의 dictionary 접근방식

# option A
example_dict = {'foo': 'bar'}

if example_dict.has_key('foo'):
  print(d['foo'])
else:
  print('Does not exists')

# option B
example_dict = {'foo': 'bar'}
search_value = example_dict.get('foo', 'Does not exists')
print(search_value)

Python의 숫자 연산, 어느 쪽이 더 직관적인가요?

# option A
def compare_number(number):
    if x > 5 and x < 15:
        return True
    return False

# option B
def compare_number(number):
    if 5 < number < 15:
        return True
    return False

Multiple Values 리턴 vs Object 리턴

# option A
def get_user():
  name = "foo"
  address = "bar"
  age = 30

  return name, address, age

name, address, age = get_user()

# option B
def get_user():
  address = "bar"
  age = 30

  return {
    name: name,
    address: address,
    age: age
  }

userinfo = get_user()

Python의 리스트 unpacking: 어느 코드를 더 선호하시나요?

# option A
>>> example = [1, 2, 3, 4, 5]
>>> a = example[0]
>>> b = example[1:4]
>>> c = example[4]
a = 1
b = [2, 3, 4]
c = [5]

# option B
>>> example = [1, 2, 3, 4, 5]
>>> a, *b, c = example
a = 1
b = [2, 3, 4]
c = [5]

Bad :

my_very_big_string = """For a long time I used to go to bed early. Sometimes, \
    when I had put out my candle, my eyes would close so quickly that I had not even \
    time to say “I’m going to sleep.”"""

from some.deep.module.inside.a.module import a_nice_function, another_nice_function, \
    yet_another_nice_function

Good :

my_very_big_string = (
    "For a long time I used to go to bed early. Sometimes, "
    "when I had put out my candle, my eyes would close so quickly "
    "that I had not even time to say “I’m going to sleep.”"
)

from some.deep.module.inside.a.module import (
    a_nice_function, another_nice_function, yet_another_nice_function)

Bad:

if attr == True:
    print('True!')

if attr == None:
    print('attr is None!')

Good:

# Just check the value
if attr:
    print('attr is truthy!')

# or check for the opposite
if not attr:
    print('attr is falsey!')

# or, since None is considered false, explicitly check for it
if attr is None:
    print('attr is None!')

Modifying the original list can be risky if there are other variables referencing it. But you can use slice assignment if you really want to do that.

# replace the contents of the original list
sequence[::] = [value for value in sequence if value != x]

https://python-guide-kr.readthedocs.io/ko/latest/writing/style.html

'Programming > Python' 카테고리의 다른 글

Functools(정리중)  (0) 2023.03.21