🌎
Go! Raymond
LinkedinGithub
  • 🤚Welcome!
  • 👨‍💻About Me
  • 🗒️Blog
    • Not just a technical blog
    • First Working Day After Leaving Trading Floor
  • 🇻🇳Work/Life in Saigon
    • Life in Saigon
      • 🪙胡志明市最佳換匯場所
      • 🥜五郡安東市場 | 伴手禮堅果類
      • 💸越南什麼東西便宜?
      • ☕胡志明工作咖啡廳
    • VN Market
      • 📒Vietnam Stock Market 101
      • 📈Major Equity Index
      • Market Research
        • 越南盾VND長期貶勢
  • 💻Technology
    • Data
      • Business Intelligence Platform
        • 📈Streamlit
          • Install and Create a Streamlit Project
      • 💾Storage | Database
        • How to install MySQL on your computer with Docker?
    • Docker
      • Docker Basic
    • Python
      • Speed up Python
        • Asynchronous
      • Clean Code in Python
        • 命名(Naming)
        • 寫法
    • Web Development
      • FastAPI
        • 建立API
        • 回傳HTML
      • RESTful API是什麼?
    • Office Automation
      • Word Template with Python
    • Task Automation
      • Rocketry
        • Example of historical stock price update (Rocketry)
      • Prefect
    • 💻How to build your own VPN server?
  • 🚀Startup
    • Y Combinator - Startup School
      • Should You Start A Startup?
  • 🌎Travel
    • 🏔️Himalaya, Nepal
      • 🗒️How to apply Nepal travel visa as Taiwanese?
      • 🏔️Annapurna Circuit Trek (ACT)
        • 🎒Equipments checklist
Powered by GitBook
On this page
  1. Technology
  2. Python
  3. Clean Code in Python

寫法

有些人會很喜歡用一些比較聰明簡短的方式來撰寫,但有時團隊中會有菜鳥或初學者時,就會出現滿臉問號。

聰明簡短的方式:

users = [{"first_name": "Helen", "age": 39},
         {"first_name": "Buck", "age": 10},
         {"first_name": "anni", "age": 9}
        ]

users = sorted(users, key = lambda user: user["first_name"].lower())

上面的程式碼使用一行程式碼就完成計算,除了對新手稍微不友善外,可能還遺漏了一些檢查等過程,可以修改為以下:

users = [{"first_name": "Helen", "age": 39},
         {"first_name": "Buck", "age": 10},
         {"first_name": "anni", "age": 9}
        ]

def get_user_name(users):
    """將名字轉換為小寫"""
    return users["first_name"].lower()

def get_sorted_dictionary(users):
    """檢查型態與長度,並依照first_name進行排序"""
    if not isinstance(users, dict):
        raise ValueError("Not a correct dictionary")
    if len(users) == 0:
        raise ValueError("Empty dictionary")
        
    users_by_name = sorted(users, key = get_user_name)
    return users_by_name

透過額外建立兩個函數,可以讓思慮更為清晰,除了增加可讀性外,亦可進行資料格式檢查,以幫助後面的debug與測試流程。

過於簡潔方式:

if val: # Will work when val is not None
# 

建議方式:

if val is not None: # Make sure only None value will be false

Previous命名(Naming)NextWeb Development

Last updated 1 year ago

💻