-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSample.py
More file actions
83 lines (59 loc) · 2.56 KB
/
Sample.py
File metadata and controls
83 lines (59 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import datetime
import locale
import gettext
# Set up gettext (only English & French, but French translations missing some keys)
locales = {
"en": gettext.translation("messages", localedir="locales", languages=["en"], fallback=True),
"fr": gettext.translation("messages", localedir="locales", languages=["fr"], fallback=True),
}
current_locale = "en"
_ = locales[current_locale].gettext
orders = [
{"id": 1, "customer": "Alice", "amount": 1234.56, "date": datetime.date.today()},
{"id": 2, "customer": "Bob", "amount": 98765.43, "date": datetime.date.today()},
]
def switch_language(lang):
global _, current_locale
if lang in locales:
current_locale = lang
_ = locales[lang].gettext
else:
print(f"Language {lang} not supported, falling back to English")
current_locale = "en"
_ = locales["en"].gettext
def add_order(customer, amount):
today = datetime.date.today()
# ❌ BAD: Hardcoded English + concatenation
print("Order for " + customer + " created on " + str(today))
# ✅ GOOD: Proper i18n message
print(_("Order for {customer} created on {date}").format(customer=customer, date=today))
orders.append({"id": len(orders) + 1, "customer": customer, "amount": amount, "date": today})
def list_orders():
print(_("Order List"))
print("------------")
for o in orders:
# ❌ BAD: Hardcoded date format
print(f"{o['customer']} | {o['date'].strftime('%m/%d/%Y')} | ${o['amount']:.2f}")
# ✅ GOOD: Locale-aware formatting
locale.setlocale(locale.LC_ALL, current_locale)
formatted_date = o['date'].strftime(locale.nl_langinfo(locale.D_FMT))
formatted_amount = locale.currency(o['amount'], grouping=True)
print(f"{o['customer']} | {formatted_date} | {formatted_amount}")
def summary():
total = sum(o["amount"] for o in orders)
# ❌ BAD: Hardcoded string
print("Total Orders: " + str(len(orders)))
print("Total Revenue: $" + str(total))
# ✅ GOOD: Localized message
print(_("Total Orders: {count}").format(count=len(orders)))
print(_("Total Revenue: {revenue}").format(revenue=locale.currency(total, grouping=True)))
if __name__ == "__main__":
print(_("Welcome to Order Management System"))
list_orders()
add_order("Charlie", 555.75)
print("\nAfter Adding Order:")
list_orders()
summary()
print("\nSwitching to French (missing translations -> fallback):")
switch_language("fr")
list_orders()