Skip to content

Instantly share code, notes, and snippets.

@bachloxo
Forked from JohnStuartRutledge/python_idioms.md
Last active November 7, 2022 14:47
Show Gist options
  • Save bachloxo/32234c787f8b09ec89faff58d4db8d2b to your computer and use it in GitHub Desktop.
Save bachloxo/32234c787f8b09ec89faff58d4db8d2b to your computer and use it in GitHub Desktop.

Revisions

  1. bachloxo revised this gist Nov 7, 2022. 1 changed file with 4 additions and 4 deletions.
    8 changes: 4 additions & 4 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -40,10 +40,10 @@ Special cases aren't special enough to break the rules. / Các trường hợp
    Although practicality beats purity. / Mặc dù tính thực tế đánh bại sự thuần khiết.
    Errors should never pass silently. / Những sai sót không bao giờ nên trôi qua một cách âm thầm.
    Unless explicitly silenced. / Trừ khi im lặng rõ ràng.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    In the face of ambiguity, refuse the temptation to guess. / Khi đối mặt với sự mơ hồ, hãy từ chối sự cám dỗ của sự phỏng đoán
    There should be one-- and preferably only one --obvious way to do it. / Nên có một-- và tốt nhất là chỉ có một - cách thức đơn giản để làm điều đó.
    Although that way may not be obvious at first unless you're Dutch. / Mặc dù cách đó có thể không rõ ràng lúc đầu trừ khi bạn là người Hà Lan.
    Now is better than never. / Bây giờ tốt hơn là không bao giờ
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a **BAD** idea.
    If the implementation is easy to explain, it may be a **GOOD** idea.
  2. bachloxo revised this gist Nov 7, 2022. 1 changed file with 11 additions and 11 deletions.
    22 changes: 11 additions & 11 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -29,17 +29,17 @@ on your command line, and type the words, "import this."
    >>> import this
    The Zen of Python, by Tim Peters
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    Beautiful is better than ugly. / Đẹp còn hơn xấu.
    Explicit is better than implicit. / Rõ ràng tốt hơn là ngầm hiểu.
    Simple is better than complex. / Đơn gi tốt hơn là phức hợp.
    Complex is better than complicated. / Phức hợp là tốt hơn phức tạp.
    Flat is better than nested. / Phẳng là tốt hơn lồng vào nhau.
    Sparse is better than dense. / Thưa thớt tốt hơn dày đặc.
    Readability counts. / Số lượng khả năng đọc.
    Special cases aren't special enough to break the rules. / Các trường hợp đặc biệt không đủ đặc biệt để phá vỡ các quy tắc.
    Although practicality beats purity. / Mặc dù tính thực tế đánh bại sự thuần khiết.
    Errors should never pass silently. / Những sai sót không bao giờ nên trôi qua một cách âm thầm.
    Unless explicitly silenced. / Trừ khi im lặng rõ ràng.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
  3. bachloxo revised this gist Nov 7, 2022. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -424,7 +424,7 @@ if any([a, b, c]):
    Be careful how you use the **is** operator when checking for empty/unset variables.
    Inherently falsy values like None, [], (), "", '', and 0 do not all mean the same thing.

    / Hãy cẩn thận cách bạn sử dụng toán tử ** is ** khi kiểm tra các biến trống / chưa đặt.
    Hãy cẩn thận cách bạn sử dụng toán tử **is** khi kiểm tra các biến empty/unset.
    Vốn dĩ các giá trị giả như Không, [], (), "", '' và 0 không phải tất cả đều có nghĩa giống nhau.

    **BAD**
    @@ -485,7 +485,7 @@ print(x) # prints 2

    ```

    Take advantage of extended slice notation to reverse a string / Tận dụng ký hiệu lát cắt mở rộng để đảo ngược một chuỗi
    Take advantage of extended slice notation to reverse a string / Tận dụng extended slice để đảo ngược một chuỗi

    **BAD**
    ```python
  4. bachloxo revised this gist Nov 7, 2022. 1 changed file with 33 additions and 51 deletions.
    84 changes: 33 additions & 51 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -70,7 +70,7 @@ def my_function_name():
    pass
    ```

    Indicate seperate words in class names using CamelCase
    Indicate seperate words in class names using CamelCase /
    Chỉ ra các từ riêng biệt trong tên lớp bằng CamelCase

    ```python
    @@ -79,8 +79,7 @@ class MyClassName(object):
    ```

    Prefix a single underscore to class members/functions meant for internal use only

    Bắt đầu một dấu gạch dưới duy nhất cho các thành viên / chức năng của lớp chỉ dành cho mục đích sử dụng nội bộ
    / Bắt đầu một dấu gạch dưới duy nhất cho các thành viên / chức năng của lớp chỉ dành cho mục đích sử dụng nội bộ

    ```python
    class MyClassName(object):
    @@ -89,7 +88,8 @@ class MyClassName(object):
    ```

    Use all caps to indicate constants
    Sử dụng tất cả các chữ hoa để biểu thị các hằng số
    / Sử dụng tất cả các chữ hoa để biểu thị các hằng số

    ```python
    class ConnectDB(object):
    DB = "mysql",
    @@ -101,7 +101,7 @@ class ConnectDB(object):

    ## List of **GOOD** and **BAD** Examples

    Use 4 spaces per indentation level
    Use 4 spaces per indentation level / Sử dụng 4 dấu cách cho mỗi mức thụt lề

    **BAD**
    ```python
    @@ -114,7 +114,7 @@ if x is True:
    print(x)
    ```

    Limit the length of your lines to 79 characters in width
    Limit the length of your lines to 79 characters in width /
    Giới hạn chiều dài dòng của bạn ở 79 ký tự chiều rộng

    **BAD**
    @@ -129,9 +129,7 @@ def my_function(a, b, c):
    a, b, c)
    ```

    Create readable multi-line text with the use of parentheses

    Tạo văn bản nhiều dòng có thể đọc được bằng cách sử dụng dấu ngoặc đơn
    Create readable multi-line text with the use of parentheses / Tạo văn bản nhiều dòng có thể đọc được bằng cách sử dụng dấu ngoặc đơn

    **BAD**
    ```python
    @@ -148,7 +146,7 @@ big_string = (
    )
    ```

    In general, try to only import one module per line
    In general, try to only import one module per line / Nói chung, hãy cố gắng chỉ nhập một mô-đun trên mỗi dòng

    **BAD**
    ```python
    @@ -161,8 +159,7 @@ import sys
    import requests
    ```

    Avoid using a temporary variable when swapping two variables
    Tránh sử dụng một biến tạm thời khi hoán đổi hai biến
    Avoid using a temporary variable when swapping two variables / Tránh sử dụng một biến tạm thời khi hoán đổi hai biến

    **BAD**
    ```python
    @@ -175,7 +172,7 @@ b = c
    a, b = b, a
    ```

    Use tuples to unpack data
    Use tuples to unpack data / Sử dụng bộ giá trị để lấy dữ liệu

    **BAD**
    ```python
    @@ -190,8 +187,7 @@ li = [1, 2, 3]
    (a, b, c) = li
    ```

    Use ''.join() on an empty string to concatonate a collection of strings
    Sử dụng '' .join () trên một chuỗi trống để nối một tập hợp các chuỗi
    Use ''.join() on an empty string to concatonate a collection of strings / Sử dụng '' .join () trên một chuỗi trống để nối một tập hợp các chuỗi

    **BAD**
    ```python
    @@ -206,8 +202,7 @@ li = ['a', 'b', 'c']
    result = ''.join(li)
    ```

    Use dict.get() to return a default value from a dictionary
    Sử dụng dict.get () để trả về giá trị mặc định từ dictionary
    Use dict.get() to return a default value from a dictionary / Sử dụng dict.get () để trả về giá trị mặc định từ dictionary

    **BAD**
    ```python
    @@ -222,8 +217,7 @@ else:
    x = my_dict.get('item', 'fallback value')
    ```

    Open files using using the with statement
    Mở tệp bằng câu lệnh with
    Open files using using the with statement / Mở tệp bằng câu lệnh with

    **BAD**
    ```python
    @@ -240,7 +234,7 @@ with open(path_to_file) as f:
    # no need to call close()
    ```

    Avoid repeating a variable within a compound if statement
    Avoid repeating a variable within a compound if statement / Tránh lặp lại một biến trong câu lệnh if ghép

    **BAD**
    ```python
    @@ -253,8 +247,7 @@ if name in ('Tom', 'Sam', 'Ron'):
    pass
    ```

    Don't place conditional code on the same line as the colon
    (Không đặt mã có điều kiện trên cùng một dòng với dấu hai chấm)
    Don't place conditional code on the same line as the colon / Không đặt mã có điều kiện trên cùng một dòng với dấu hai chấm

    **BAD**
    ```python
    @@ -266,8 +259,7 @@ if item:
    print(item)
    ```

    Avoid putting multiple statements on a single line
    (Tránh đặt nhiều câu lệnh trên một dòng)
    Avoid putting multiple statements on a single line / Tránh đặt nhiều câu lệnh trên một dòng

    **BAD**
    ```python
    @@ -280,8 +272,7 @@ if condition:
    my_other_function()
    ```

    Use list comprehensions to create lists that are subsets of existing data
    (Sử dụng khả năng hiểu danh sách để tạo danh sách là tập hợp con của dữ liệu hiện có)
    Use list comprehensions to create lists that are subsets of existing data / Sử dụng khả năng hiểu danh sách để tạo danh sách là tập hợp con của dữ liệu hiện có

    **BAD**
    ```python
    @@ -297,8 +288,7 @@ l1 = range(1, 100)
    l2 = [x for x in l1 if is_prime(x)]
    ```

    Use the 'in' keyword to iterate over an Iterable
    (Sử dụng từ khóa 'in' để lặp lại một Lặp lại)
    Use the 'in' keyword to iterate over an Iterable / Sử dụng từ khóa 'in' để lặp lại một Lặp lại

    **BAD**
    ```python
    @@ -315,8 +305,7 @@ for element in li:
    print(element)
    ```

    Use the 'enumerate' built-in function to keep count on an Iterable
    (Sử dụng hàm tích hợp 'liệt kê' để tiếp tục đếm trên một Lặp lại)
    Use the 'enumerate' built-in function to keep count on an Iterable / Sử dụng hàm tích hợp 'liệt kê' để tiếp tục đếm trên một Lặp lại

    **BAD**
    ```python
    @@ -332,8 +321,7 @@ for index, item in enumerate(li):
    print(index, item)
    ```

    Create a length-N list composed of the same specific item
    (Tạo một danh sách dài-N bao gồm cùng một mục cụ thể)
    Create a length-N list composed of the same specific item / Tạo một danh sách dài-N bao gồm cùng một mục cụ thể

    **BAD**
    ```python
    @@ -346,8 +334,7 @@ for x in range(1,5):
    four_nones = [None] * 4
    ```

    Create a length-N list composed of empty lists
    (Tạo một danh sách dài-N bao gồm các danh sách trống)
    Create a length-N list composed of empty lists / Tạo một danh sách dài-N bao gồm các danh sách trống

    **BAD**
    ```python
    @@ -360,8 +347,7 @@ for _ in range(1, 5):
    li = [[] for _ in range(4)]
    ```

    Use isinstance() to do object type comparisons
    (Sử dụng isinstance () để so sánh loại đối tượng)
    Use isinstance() to do object type comparisons / Sử dụng isinstance () để so sánh loại đối tượng

    **BAD**
    ```python
    @@ -376,8 +362,7 @@ if isinstance(x, int):
    print('x is an int')
    ```

    For strings, lists, and tuples, use the fact that empty sequences are false
    (Đối với chuỗi, danh sách và bộ giá trị, hãy sử dụng thực tế là các chuỗi trống là sai)
    For strings, lists, and tuples, use the fact that empty sequences are false / Đối với chuỗi, danh sách và bộ giá trị, hãy sử dụng thực tế là các chuỗi trống là sai

    **BAD**
    ```python
    @@ -393,8 +378,7 @@ if not x:
    print('x is false')
    ```

    Avoid using a mutable values as a default function parameter
    (Tránh sử dụng các giá trị có thể thay đổi làm tham số hàm mặc định)
    Avoid using a mutable values as a default function parameter / Tránh sử dụng các giá trị có thể thay đổi làm tham số hàm mặc định

    **BAD**
    ```python
    @@ -409,8 +393,7 @@ def fn(x=None):
    x.append(1)
    print(x)
    ```
    Check that all items in a large set of items are true
    (Kiểm tra xem tất cả các mục trong một tập hợp lớn các mục có đúng không)
    Check that all items in a large set of items are true / Kiểm tra xem tất cả các mục trong một tập hợp lớn các mục có đúng không

    **BAD**
    ```python
    @@ -424,8 +407,7 @@ if all([a, b, c, d, e, f, g, h]):
    print('all true')
    ```

    Check if at least one item in a set of three or more items are true
    (Kiểm tra xem ít nhất một mục trong bộ ba mục trở lên có đúng không)
    Check if at least one item in a set of three or more items are true / Kiểm tra xem ít nhất một mục trong bộ ba mục trở lên có đúng không

    **BAD**
    ```python
    @@ -441,8 +423,9 @@ if any([a, b, c]):

    Be careful how you use the **is** operator when checking for empty/unset variables.
    Inherently falsy values like None, [], (), "", '', and 0 do not all mean the same thing.
    (Hãy cẩn thận cách bạn sử dụng toán tử ** is ** khi kiểm tra các biến trống / chưa đặt.
    Vốn dĩ các giá trị giả như Không, [], (), "", '' và 0 không phải tất cả đều có nghĩa giống nhau.)

    / Hãy cẩn thận cách bạn sử dụng toán tử ** is ** khi kiểm tra các biến trống / chưa đặt.
    Vốn dĩ các giá trị giả như Không, [], (), "", '' và 0 không phải tất cả đều có nghĩa giống nhau.

    **BAD**
    ```python
    @@ -465,8 +448,7 @@ if x:
    # neither None or [] will pass the if statment
    ```

    Be aware of scope. Using the same variable name for a global and local variables can lead to errors
    (Hãy nhận biết về phạm vi. Sử dụng cùng một tên biến cho biến cục bộ và toàn cục có thể dẫn đến lỗi)
    Be aware of scope. Using the same variable name for a global and local variables can lead to errors / Hãy nhận biết về phạm vi. Sử dụng cùng một tên biến cho biến cục bộ và toàn cục có thể dẫn đến lỗi

    **BAD**
    ```python
    @@ -503,8 +485,7 @@ print(x) # prints 2

    ```

    Take advantage of extended slice notation to reverse a string
    (Tận dụng ký hiệu lát cắt mở rộng để đảo ngược một chuỗi)
    Take advantage of extended slice notation to reverse a string / Tận dụng ký hiệu lát cắt mở rộng để đảo ngược một chuỗi

    **BAD**
    ```python
    @@ -549,7 +530,8 @@ foo = Counter(ls)
    print(foo) # Counter({'a': 3, 'b': 1, 'c': 1})
    ```

    Use for..else to run some code if the break statment is never reached.
    Use for..else to run some code if the break statment is never reached. / Sử dụng for..else để chạy một số mã nếu câu lệnh break không bao giờ đạt được.

    **BAD**
    ```python
    # bad example here that uses a tracking variable to determine if break has run or not
  5. bachloxo revised this gist Nov 7, 2022. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -79,6 +79,7 @@ class MyClassName(object):
    ```

    Prefix a single underscore to class members/functions meant for internal use only

    Bắt đầu một dấu gạch dưới duy nhất cho các thành viên / chức năng của lớp chỉ dành cho mục đích sử dụng nội bộ

    ```python
    @@ -130,6 +131,8 @@ def my_function(a, b, c):

    Create readable multi-line text with the use of parentheses

    Tạo văn bản nhiều dòng có thể đọc được bằng cách sử dụng dấu ngoặc đơn

    **BAD**
    ```python
    big_string = """This is the first line in the text \
  6. bachloxo revised this gist Nov 7, 2022. 1 changed file with 10 additions and 0 deletions.
    10 changes: 10 additions & 0 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -71,19 +71,24 @@ def my_function_name():
    ```

    Indicate seperate words in class names using CamelCase
    Chỉ ra các từ riêng biệt trong tên lớp bằng CamelCase

    ```python
    class MyClassName(object):
    pass
    ```

    Prefix a single underscore to class members/functions meant for internal use only
    Bắt đầu một dấu gạch dưới duy nhất cho các thành viên / chức năng của lớp chỉ dành cho mục đích sử dụng nội bộ

    ```python
    class MyClassName(object):
    def _internal_function(self):
    pass
    ```

    Use all caps to indicate constants
    Sử dụng tất cả các chữ hoa để biểu thị các hằng số
    ```python
    class ConnectDB(object):
    DB = "mysql",
    @@ -109,6 +114,7 @@ if x is True:
    ```

    Limit the length of your lines to 79 characters in width
    Giới hạn chiều dài dòng của bạn ở 79 ký tự chiều rộng

    **BAD**
    ```python
    @@ -153,6 +159,7 @@ import requests
    ```

    Avoid using a temporary variable when swapping two variables
    Tránh sử dụng một biến tạm thời khi hoán đổi hai biến

    **BAD**
    ```python
    @@ -181,6 +188,7 @@ li = [1, 2, 3]
    ```

    Use ''.join() on an empty string to concatonate a collection of strings
    Sử dụng '' .join () trên một chuỗi trống để nối một tập hợp các chuỗi

    **BAD**
    ```python
    @@ -196,6 +204,7 @@ result = ''.join(li)
    ```

    Use dict.get() to return a default value from a dictionary
    Sử dụng dict.get () để trả về giá trị mặc định từ dictionary

    **BAD**
    ```python
    @@ -211,6 +220,7 @@ x = my_dict.get('item', 'fallback value')
    ```

    Open files using using the with statement
    Mở tệp bằng câu lệnh with

    **BAD**
    ```python
  7. bachloxo revised this gist Nov 7, 2022. 1 changed file with 16 additions and 0 deletions.
    16 changes: 16 additions & 0 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -241,6 +241,7 @@ if name in ('Tom', 'Sam', 'Ron'):
    ```

    Don't place conditional code on the same line as the colon
    (Không đặt mã có điều kiện trên cùng một dòng với dấu hai chấm)

    **BAD**
    ```python
    @@ -253,6 +254,7 @@ if item:
    ```

    Avoid putting multiple statements on a single line
    (Tránh đặt nhiều câu lệnh trên một dòng)

    **BAD**
    ```python
    @@ -266,6 +268,7 @@ if condition:
    ```

    Use list comprehensions to create lists that are subsets of existing data
    (Sử dụng khả năng hiểu danh sách để tạo danh sách là tập hợp con của dữ liệu hiện có)

    **BAD**
    ```python
    @@ -282,6 +285,7 @@ l2 = [x for x in l1 if is_prime(x)]
    ```

    Use the 'in' keyword to iterate over an Iterable
    (Sử dụng từ khóa 'in' để lặp lại một Lặp lại)

    **BAD**
    ```python
    @@ -299,6 +303,7 @@ for element in li:
    ```

    Use the 'enumerate' built-in function to keep count on an Iterable
    (Sử dụng hàm tích hợp 'liệt kê' để tiếp tục đếm trên một Lặp lại)

    **BAD**
    ```python
    @@ -315,6 +320,7 @@ for index, item in enumerate(li):
    ```

    Create a length-N list composed of the same specific item
    (Tạo một danh sách dài-N bao gồm cùng một mục cụ thể)

    **BAD**
    ```python
    @@ -328,6 +334,7 @@ four_nones = [None] * 4
    ```

    Create a length-N list composed of empty lists
    (Tạo một danh sách dài-N bao gồm các danh sách trống)

    **BAD**
    ```python
    @@ -341,6 +348,7 @@ li = [[] for _ in range(4)]
    ```

    Use isinstance() to do object type comparisons
    (Sử dụng isinstance () để so sánh loại đối tượng)

    **BAD**
    ```python
    @@ -356,6 +364,7 @@ if isinstance(x, int):
    ```

    For strings, lists, and tuples, use the fact that empty sequences are false
    (Đối với chuỗi, danh sách và bộ giá trị, hãy sử dụng thực tế là các chuỗi trống là sai)

    **BAD**
    ```python
    @@ -372,6 +381,7 @@ if not x:
    ```

    Avoid using a mutable values as a default function parameter
    (Tránh sử dụng các giá trị có thể thay đổi làm tham số hàm mặc định)

    **BAD**
    ```python
    @@ -387,6 +397,7 @@ def fn(x=None):
    print(x)
    ```
    Check that all items in a large set of items are true
    (Kiểm tra xem tất cả các mục trong một tập hợp lớn các mục có đúng không)

    **BAD**
    ```python
    @@ -401,6 +412,7 @@ if all([a, b, c, d, e, f, g, h]):
    ```

    Check if at least one item in a set of three or more items are true
    (Kiểm tra xem ít nhất một mục trong bộ ba mục trở lên có đúng không)

    **BAD**
    ```python
    @@ -416,6 +428,8 @@ if any([a, b, c]):

    Be careful how you use the **is** operator when checking for empty/unset variables.
    Inherently falsy values like None, [], (), "", '', and 0 do not all mean the same thing.
    (Hãy cẩn thận cách bạn sử dụng toán tử ** is ** khi kiểm tra các biến trống / chưa đặt.
    Vốn dĩ các giá trị giả như Không, [], (), "", '' và 0 không phải tất cả đều có nghĩa giống nhau.)

    **BAD**
    ```python
    @@ -439,6 +453,7 @@ if x:
    ```

    Be aware of scope. Using the same variable name for a global and local variables can lead to errors
    (Hãy nhận biết về phạm vi. Sử dụng cùng một tên biến cho biến cục bộ và toàn cục có thể dẫn đến lỗi)

    **BAD**
    ```python
    @@ -476,6 +491,7 @@ print(x) # prints 2
    ```

    Take advantage of extended slice notation to reverse a string
    (Tận dụng ký hiệu lát cắt mở rộng để đảo ngược một chuỗi)

    **BAD**
    ```python
  8. @JohnStuartRutledge JohnStuartRutledge revised this gist Nov 29, 2017. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -9,6 +9,7 @@ Many of the examples were taken from the following resources:
    - [Writing Idiomatic Python](http://www.jeffknupp.com/blog/2012/10/04/writing-idiomatic-python/)
    - [Python Best Practice Patterns](http://stevenloria.com/python-best-practice-patterns-by-vladimir-keleshev-notes/)
    - [Python-tips-tricks-and-idioms](https://codefisher.org/catch/blog/2015/01/27/python-tips-tricks-and-idioms)
    - [Little book of Python anti-paterns](https://docs.quantifiedcode.com/python-anti-patterns/)


    ## Summary
  9. @JohnStuartRutledge JohnStuartRutledge revised this gist Nov 15, 2017. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -560,4 +560,6 @@ Incorporate a linting tool like `pyflakes` or `pylint` into your IDE.

    Learn to approach unit tests as a brain-storming exercise on how best to write your application.

    In general prefer smaller individual functions dedicated to doing a single thing to larger functions that do many things.

    Give every function a docstring.
  10. @JohnStuartRutledge JohnStuartRutledge revised this gist Nov 15, 2017. 1 changed file with 5 additions and 5 deletions.
    10 changes: 5 additions & 5 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -550,14 +550,14 @@ else: # no break encountered

    # Misc Observations For Programming in Python

    use `virtualenv` - don't install python packages at the system level
    Use `virtualenv` - don't install python packages at the system level

    take advantage of ipython/Juptyers profiling functions like `%time` and `%prun` to profile code.
    Take advantage of ipython/Juptyers profiling functions like `%time` and `%prun` to profile code.

    avoid `*args` and `**kwargs` unless you need them - they make function signatures hard to read and code-completion less helpful
    Avoid `*args` and `**kwargs` unless you need them - they make function signatures hard to read and code-completion less helpful

    incorperate a linting tool like `pyflakes` or `pylint` into your IDE.
    Incorporate a linting tool like `pyflakes` or `pylint` into your IDE.

    learn to approach unit tests as a brain-storming exercise on how best to write your application.
    Learn to approach unit tests as a brain-storming exercise on how best to write your application.


  11. @JohnStuartRutledge JohnStuartRutledge revised this gist Nov 15, 2017. 1 changed file with 15 additions and 1 deletion.
    16 changes: 15 additions & 1 deletion python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -546,4 +546,18 @@ else: # no break encountered

    def __repr__(self):
    return 'Example(x={})'.format(self.x)
    ```
    ```

    # Misc Observations For Programming in Python

    use `virtualenv` - don't install python packages at the system level

    take advantage of ipython/Juptyers profiling functions like `%time` and `%prun` to profile code.

    avoid `*args` and `**kwargs` unless you need them - they make function signatures hard to read and code-completion less helpful

    incorperate a linting tool like `pyflakes` or `pylint` into your IDE.

    learn to approach unit tests as a brain-storming exercise on how best to write your application.


  12. @JohnStuartRutledge JohnStuartRutledge revised this gist Nov 8, 2017. 1 changed file with 0 additions and 15 deletions.
    15 changes: 0 additions & 15 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -354,21 +354,6 @@ if isinstance(x, int):
    print('x is an int')
    ```

    When checking the instance of a string, make sure you allow for unicode (python 2.7)

    **BAD**
    ```python
    x = 'hi'
    if isinstance(x, str):
    print('x is a str')
    ```
    **GOOD**
    ```python
    x = 'hi'
    if isinstance(x, basestring):
    print('x is a str')
    ```

    For strings, lists, and tuples, use the fact that empty sequences are false

    **BAD**
  13. @JohnStuartRutledge JohnStuartRutledge revised this gist Nov 8, 2017. 1 changed file with 12 additions and 13 deletions.
    25 changes: 12 additions & 13 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -85,9 +85,9 @@ class MyClassName(object):
    Use all caps to indicate constants
    ```python
    class ConnectDB(object):
    DATABASE = "mysql",
    USER = "Steve",
    PASS = "fzHx$"
    DB = "mysql",
    USER = "Steve",
    PASS = "fzHx$"
    def __init__(self):
    pass
    ```
    @@ -98,12 +98,12 @@ Use 4 spaces per indentation level

    **BAD**
    ```python
    if x == True:
    if x is True:
    print(x)
    ```
    **GOOD**
    ```python
    if x == True:
    if x is True:
    print(x)
    ```

    @@ -146,8 +146,8 @@ import sys, os, requests
    ```
    **GOOD**
    ```python
    import sys
    import os
    import sys
    import requests
    ```

    @@ -331,12 +331,12 @@ Create a length-N list composed of empty lists
    **BAD**
    ```python
    li = []
    for x in range(1, 5):
    for _ in range(1, 5):
    li.append([])
    ```
    **GOOD**
    ```python
    li = [[] for _ in xrange(4)]
    li = [[] for _ in range(4)]
    ```

    Use isinstance() to do object type comparisons
    @@ -354,7 +354,7 @@ if isinstance(x, int):
    print('x is an int')
    ```

    When checking the instance of a string, make sure you allow for unicode
    When checking the instance of a string, make sure you allow for unicode (python 2.7)

    **BAD**
    ```python
    @@ -385,7 +385,7 @@ if not x:
    print('x is false')
    ```

    Avoid using a mutable value as a default function parameter
    Avoid using a mutable values as a default function parameter

    **BAD**
    ```python
    @@ -396,8 +396,7 @@ def fn(x=[]):
    **GOOD**
    ```python
    def fn(x=None):
    if x is None:
    x = []
    x = [] if x is None else x
    x.append(1)
    print(x)
    ```
    @@ -430,7 +429,7 @@ if any([a, b, c]):
    ```

    Be careful how you use the **is** operator when checking for empty/unset variables.
    Inherintly falsy values like None, [], (), "", '', and 0 do not all mean the same thing.
    Inherently falsy values like None, [], (), "", '', and 0 do not all mean the same thing.

    **BAD**
    ```python
  14. @JohnStuartRutledge JohnStuartRutledge revised this gist Dec 8, 2016. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -550,8 +550,8 @@ for f in file_list:
    else: # no break encountered
    batch_process_files(file_list)
    ```
    ## Good Practices

    ## Good Practices

    Add `__repr__` to all your classes for more beautiful debugging
    ```python
  15. @JohnStuartRutledge JohnStuartRutledge revised this gist Dec 8, 2016. 1 changed file with 14 additions and 1 deletion.
    15 changes: 14 additions & 1 deletion python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -549,4 +549,17 @@ for f in file_list:
    break
    else: # no break encountered
    batch_process_files(file_list)
    ```
    ```

    ## Good Practices

    Add `__repr__` to all your classes for more beautiful debugging
    ```python

    class Example:
    def __init__(self, x):
    self.x = x

    def __repr__(self):
    return 'Example(x={})'.format(self.x)
    ```
  16. @JohnStuartRutledge JohnStuartRutledge revised this gist Jan 30, 2015. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -8,6 +8,7 @@ Many of the examples were taken from the following resources:
    - [Hitchikers Guide to Python](http://docs.python-guide.org/en/latest/writing/style/#idioms)
    - [Writing Idiomatic Python](http://www.jeffknupp.com/blog/2012/10/04/writing-idiomatic-python/)
    - [Python Best Practice Patterns](http://stevenloria.com/python-best-practice-patterns-by-vladimir-keleshev-notes/)
    - [Python-tips-tricks-and-idioms](https://codefisher.org/catch/blog/2015/01/27/python-tips-tricks-and-idioms)


    ## Summary
  17. @JohnStuartRutledge JohnStuartRutledge revised this gist Jan 30, 2015. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -541,7 +541,7 @@ Use for..else to run some code if the break statment is never reached.
    ```

    **GOOD**
    ``python
    ```python

    for f in file_list:
    if is_img(f):
  18. @JohnStuartRutledge JohnStuartRutledge revised this gist Jan 30, 2015. 1 changed file with 17 additions and 1 deletion.
    18 changes: 17 additions & 1 deletion python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -532,4 +532,20 @@ from collections import Counter
    ls = ['a', 'a', 'b', 'c', 'a']
    foo = Counter(ls)
    print(foo) # Counter({'a': 3, 'b': 1, 'c': 1})
    ```
    ```

    Use for..else to run some code if the break statment is never reached.
    **BAD**
    ```python
    # bad example here that uses a tracking variable to determine if break has run or not
    ```

    **GOOD**
    ``python

    for f in file_list:
    if is_img(f):
    break
    else: # no break encountered
    batch_process_files(file_list)
    ```
  19. @JohnStuartRutledge JohnStuartRutledge revised this gist Jan 22, 2015. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -4,6 +4,7 @@ idiomatic (Pythonic) code.
    Many of the examples were taken from the following resources:

    - [PEP 8 - Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/)
    - [Khan Academy Style Guide](https://github.com/Khan/style-guides/blob/master/style/python.md)
    - [Hitchikers Guide to Python](http://docs.python-guide.org/en/latest/writing/style/#idioms)
    - [Writing Idiomatic Python](http://www.jeffknupp.com/blog/2012/10/04/writing-idiomatic-python/)
    - [Python Best Practice Patterns](http://stevenloria.com/python-best-practice-patterns-by-vladimir-keleshev-notes/)
  20. @JohnStuartRutledge JohnStuartRutledge revised this gist Jun 24, 2014. 1 changed file with 28 additions and 4 deletions.
    32 changes: 28 additions & 4 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -402,27 +402,27 @@ def fn(x=None):
    Check that all items in a large set of items are true

    **BAD**
    ```
    ```python
    if a and b and c and d and e and f and g and h:
    print('all true')
    ```

    **GOOD**
    ```
    ```python
    if all([a, b, c, d, e, f, g, h]):
    print('all true')
    ```

    Check if at least one item in a set of three or more items are true

    **BAD**
    ```
    ```python
    if a or b or c:
    print('at least one is true')
    ```

    **GOOD**
    ```
    ```python
    if any([a, b, c]):
    print('at least one is true')
    ```
    @@ -507,4 +507,28 @@ backward = 'hello'[::-1]
    backward = ''.join(reversed('hello'))

    print(backward) # 'olleh'
    ```

    Counting frequency

    **BAD**
    ```python
    ls = ['a', 'a', 'b', 'c', 'a']
    foo = {}
    for x in ls:
    if x in foo:
    foo[x] += 1
    else:
    foo[x] = 1

    print(foo) # {'a': 3, 'b': 1, 'c': 1}
    ```

    **GOOD**
    ```python
    from collections import Counter

    ls = ['a', 'a', 'b', 'c', 'a']
    foo = Counter(ls)
    print(foo) # Counter({'a': 3, 'b': 1, 'c': 1})
    ```
  21. @JohnStuartRutledge JohnStuartRutledge revised this gist Jun 24, 2014. 1 changed file with 15 additions and 1 deletion.
    16 changes: 15 additions & 1 deletion python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -399,7 +399,7 @@ def fn(x=None):
    x.append(1)
    print(x)
    ```
    Check for the truthiness of a large number of items at once
    Check that all items in a large set of items are true

    **BAD**
    ```
    @@ -413,6 +413,20 @@ if all([a, b, c, d, e, f, g, h]):
    print('all true')
    ```

    Check if at least one item in a set of three or more items are true

    **BAD**
    ```
    if a or b or c:
    print('at least one is true')
    ```

    **GOOD**
    ```
    if any([a, b, c]):
    print('at least one is true')
    ```

    Be careful how you use the **is** operator when checking for empty/unset variables.
    Inherintly falsy values like None, [], (), "", '', and 0 do not all mean the same thing.

  22. @JohnStuartRutledge JohnStuartRutledge revised this gist Jun 24, 2014. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -399,17 +399,17 @@ def fn(x=None):
    x.append(1)
    print(x)
    ```
    Check for the truthiness of more than two items at once
    Check for the truthiness of a large number of items at once

    **BAD**
    ```
    if a and b and c:
    if a and b and c and d and e and f and g and h:
    print('all true')
    ```

    **GOOD**
    ```
    if all([a, b, c]):
    if all([a, b, c, d, e, f, g, h]):
    print('all true')
    ```

  23. @JohnStuartRutledge JohnStuartRutledge revised this gist Jun 24, 2014. 1 changed file with 13 additions and 0 deletions.
    13 changes: 13 additions & 0 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -399,6 +399,19 @@ def fn(x=None):
    x.append(1)
    print(x)
    ```
    Check for the truthiness of more than two items at once

    **BAD**
    ```
    if a and b and c:
    print('all true')
    ```

    **GOOD**
    ```
    if all([a, b, c]):
    print('all true')
    ```

    Be careful how you use the **is** operator when checking for empty/unset variables.
    Inherintly falsy values like None, [], (), "", '', and 0 do not all mean the same thing.
  24. @JohnStuartRutledge JohnStuartRutledge revised this gist Mar 4, 2014. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -1,11 +1,12 @@
    This page is designed to give you a list of concrete examples demonstrating
    idiomatic (Pythonic) code.

    This section borrows liberally from these three resources:
    Many of the examples were taken from the following resources:

    - [PEP 8 - Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/)
    - [Hitchikers Guide to Python](http://docs.python-guide.org/en/latest/writing/style/#idioms)
    - [Writing Idiomatic Python](http://www.jeffknupp.com/blog/2012/10/04/writing-idiomatic-python/)
    - [Python Best Practice Patterns](http://stevenloria.com/python-best-practice-patterns-by-vladimir-keleshev-notes/)


    ## Summary
  25. Stu revised this gist Jul 13, 2013. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -472,11 +472,11 @@ print(backward) # 'olleh'
    ```
    **GOOD**
    ```python
    # the faster, albiet less readable approach is
    # the faster albiet less readable approach is
    backward = 'hello'[::-1]
    print(backward) # 'olleh'

    # the slower, but more readable approach is:
    # the slower but more readable approach is:
    backward = ''.join(reversed('hello'))

    print(backward) # 'olleh'
    ```
  26. Stu revised this gist Jul 13, 2013. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -472,11 +472,11 @@ print(backward) # 'olleh'
    ```
    **GOOD**
    ```python
    # this faster, albiet less readable approach is
    # the faster, albiet less readable approach is
    backward = 'hello'[::-1]
    print(backward) # 'olleh'

    # Note: a slower but more readable approach would be:
    # the slower, but more readable approach is:
    backward = ''.join(reversed('hello'))
    print(backward) # 'olleh'
    ```
  27. Stu revised this gist Jul 13, 2013. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -465,8 +465,8 @@ Take advantage of extended slice notation to reverse a string
    **BAD**
    ```python
    backward = ''
    for chr in reversed('hello'):
    backward += chr
    for c in reversed('hello'):
    backward += c

    print(backward) # 'olleh'
    ```
  28. Stu revised this gist Jul 13, 2013. 1 changed file with 1 addition and 5 deletions.
    6 changes: 1 addition & 5 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -469,18 +469,14 @@ for chr in reversed('hello'):
    backward += chr

    print(backward) # 'olleh'

    ```
    **GOOD**
    ```python

    # this faster, albiet less readable approach is
    backward = 'hello'[::-1]

    print(backward) # 'olleh'


    # Note: a slower but more readable approach would be:
    backward = ''.join(reversed('hello'))

    print(backward) # 'olleh'
    ```
  29. Stu revised this gist Jul 13, 2013. 1 changed file with 12 additions and 12 deletions.
    24 changes: 12 additions & 12 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -460,27 +460,27 @@ print(x) # prints 2

    ```

    Take advantage of slice notation to reverse a string
    Take advantage of extended slice notation to reverse a string

    **BAD**
    ```python
    mystring = 'hello'
    backward = []
    backward = ''
    for chr in reversed('hello'):
    backward += chr

    for chr in reversed(mystring):
    backward.append(chr)

    mystring = ''.join(backward)

    print(mystring) # 'olleh'
    print(backward) # 'olleh'

    ```
    **GOOD**
    ```python
    mystring = 'hello'

    mystring = [::-1]
    # this faster, albiet less readable approach is
    backward = 'hello'[::-1]

    print(backward) # 'olleh'


    print(mystring) # 'olleh'
    # Note: a slower but more readable approach would be:
    backward = ''.join(reversed('hello'))

    ```
  30. Stu revised this gist Jul 13, 2013. 1 changed file with 25 additions and 0 deletions.
    25 changes: 25 additions & 0 deletions python_idioms.md
    Original file line number Diff line number Diff line change
    @@ -459,3 +459,28 @@ fn() # prints 1
    print(x) # prints 2

    ```

    Take advantage of slice notation to reverse a string

    **BAD**
    ```python
    mystring = 'hello'
    backward = []

    for chr in reversed(mystring):
    backward.append(chr)

    mystring = ''.join(backward)

    print(mystring) # 'olleh'

    ```
    **GOOD**
    ```python
    mystring = 'hello'

    mystring = [::-1]

    print(mystring) # 'olleh'

    ```