叩頂窩客 - KodingWork
  • Stable Diffusion
  • Blockchain
  • Arduino
    • ESP32
    • Raspberry Pi Pico
  • Raspberry Pi
    • Raspberry Pi
    • Odroid HC4
    • Banana Pi
  • 創客計畫
    • AI 神經網路自走車
    • 智慧家居
  • Python
  • AWS
  • 開發哲學
  • 關於作者 J
Stable Diffusion
Blockchain
Arduino
    ESP32
    Raspberry Pi Pico
Raspberry Pi
    Raspberry Pi
    Odroid HC4
    Banana Pi
創客計畫
    AI 神經網路自走車
    智慧家居
Python
AWS
開發哲學
關於作者 J
叩頂窩客 - KodingWork
  • Stable Diffusion
  • Blockchain
  • Arduino
    • ESP32
    • Raspberry Pi Pico
  • Raspberry Pi
    • Raspberry Pi
    • Odroid HC4
    • Banana Pi
  • 創客計畫
    • AI 神經網路自走車
    • 智慧家居
  • Python
  • AWS
  • 開發哲學
  • 關於作者 J
Python•那些踩過的坑

Python 詭譎的 default parameter value ,由踩坑來學習!

2021-03-19 by J No Comments

有時候錯誤訊息只是表象,root cause 並非如字面上的提示如此簡單!今天分享一個跑測試時遇到的坑,使用 django 內建的 test 框架跑測試,所以建立測試 db 由 django 負責,在跑測試前會建立 test db 並把 table 開好。結果這次在跑開表前就看到這個錯誤

django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value.

起初懷疑是 database 相關設定被改,於是檢查 settings 部分,發現 code 最近並沒有人做過修改。切到其他 branch 可以跑,但就在目前這隻 branch 會發生問題,所以看來和這隻的修改有關係。

與同事討論後,他說他之前也遇過類似的問題,那時的原因是他在 test 裡把一些 access db 的 code 寫在某些地方,導致 db 還沒建立就去 access db 而發生類似的錯誤。

仔細檢查這次的修改,發現在某些 class 的 __init__ 裡面增加了 default 設定

class AdvanceInvoiceUpdateHandler():
    def __init__(self, user, voucher_service=VoucherService()):  # set default value
        self.user = user
        self.voucher_service = voucher_service

而在 VoucherService 的 __init__ 裡面我們有 access db

class VoucherService():
    def __init__(self):
        company = Company.get_current_company()  # access db

但直覺上來說塞在 __init__ 裡面的 default VoucherService() 不應該在還沒建立 AdvanceInvoiceUpdateHandler 的時候 init 啊!

為了確認是否他是兇手,做以下修改

class VoucherService():
    def __init__(self):
	print(‘I am the ghost.’’)
        ...

再跑一次測試,果然看到 「I am the ghost.」出現在錯誤訊息之前

做以下修改解決錯誤,把 default VoucherService 往內放即可

class AdvanceInvoiceCreateHandler():
    def __init__(self, user, voucher_service=None):
        self.user = user
        self.voucher_service = voucher_service or VoucherService()

這讓我好奇 python 中 function default arguments 的規則,於是上網研究了下,得到以下結論

  1. python 的函數是物件
  2. python 的 def 是「可執行陳述式」
  3. default arguments 的值會在「跑 def 陳述」時被建立
  4. mutable object 做 default value 的時候,不能寫在 arguments 旁邊,要到 function 裡面去處理

首先要知道 python 中的東西都是 object,再來要區分出 mutable object 和 immutable object

常見可變物件(指對物件「本身」的值可以改變):
list, dict, set

常見不可變物件(指對物件「本身」的值不可改變):
int, float, string, tuple

對可變物件的 value 做修改,會發現他的記憶體位置並不改變

a = [1, 2]
print(id(a))
>>> 4320093280

a[0] = 2
print(a)
>>> [2, 2]
print(id(a))
>>> 4320093280

這部分很好理解。
那對不可變物件的 value 修改

b = 1000
print(id(b))
>>> 4320093280

b += 10
print(b)
>>> 1010
print(id(b))
>>> 4320093102

原來 b 指到 1000 這個 int object,因為 int object  不可變,所以 python 會先建立一個新的 int object 1010,再把 b 指過去(很像 C 的指標)

回到我們的要討論的初始值問題
如果我們有這個函數:

def test(data=[]):
    data.append(1)
    return data

會發現這個現象:

>>> test()
[1]
>>> test()
[1, 1]
>>> test()
[1, 1, 1]

這是因為我們設定的 default argment 「data」 所屬的空陣列 [] 在 python 初始化 test 函數時就建立在特殊 class attribute

>>> test.__defaults__
([], )

每次呼叫函數,python 都會從 __defaults__ 裡面去拿預設值,所以

>>> test()
[1]
>>> test.__defaults__
([1], )
>>> test()
[1, 1]
>>> test.__defaults__
([1, 1], )

從這個實驗可以看出

  1. default data 值是從 class attribute 拿過來設定進去
  2. 每次跑時對 data 的修改是「可變物件」的修改,因此都會去修改同一個物件

可以看成以下程式

#  呼叫第一次
data = test.__defaults__[0]
data.append(1)
print(data)
>>> [1]

# 呼叫第二次
data = test.__defaults__[0]
data.append(1)
print(data)
>>> [1, 1]

# 後面雷同

如果要設定的 default value 是可變物件,要使用以下方式

def test(data=None):
    if data is None:
        data = []

把初始值放在函數裡面去給定,這樣就能解決問題!

最後再回頭看一開始遇到的問題

class AdvanceInvoiceUpdateHandler():
    def __init__(self, user, voucher_service=VoucherService()):
        self.user = user
        self.voucher_service = voucher_service

因為我把 voucher_service 的預設值設定為 VoucherService(),所以 python 最初 initial 整份 code 的時候,就先把 VoucherService 初始化放到 __init__ 函數裡的 __default__,那時 django 還沒把 db 建立起來,而 VoucherService 初始化要 access db,程式就發生錯誤了!

真是一個背景知識很高的採坑經驗!

延伸閱讀:
如何解決 Python Decimal.quantize() 發生 InvalidOperation
被新創公司裁員後,我學到的五件事
macOS 中 Python 版本太多如何管理?試試 pyenv 吧!

參考資料

Default Parameter Values in Python
Python constructor and default value [duplicate]
“Least Astonishment” and the Mutable Default Argument
[Python 基礎教學] 什麼是 Immutable & Mutable objects

Continue reading
Share:
Golang•Python•那些踩過的坑

入坑!SQLAlchemy 和 GORM 的 first() 函數

2021-02-28 by J No Comments

一樣是 first 函數,在 SQLAlchemy 和 GORM 卻有不同的行為?使用上該怎麼區分?

由於之前主力語言是 python,orm 大多使用 SQLAlchemy。學習 golang 時轉用 GORM 作為 orm,容易把之前在 SQLAlchemy 的語法習慣帶入使用,導致入莫名的坑!今日我們來看看兩者的 first 函數差異。

差異

假設有一張表 test_score 定義如下

ID (int)date (date)score (int)
12021-02-28100
22021-03-0187
32021-03-0267

此時如果我心中想要達成以下 SQL

SELECT * FROM test_score ORDER BY date DESC LIMIT 1;

在 SQLAlchemy 中會這麼寫

sess.query(TestScore).order_by(TestScore.date.desc()).first()

就能達成一樣的 SQL。

但如果在 GORM 這樣寫

db.Order("date desc").First(&testScore)

build 出來的 SQL 卻是這樣

SELECT * FROM test_score ORDER BY date desc, id LIMIT 1;

多了一個對 id sort 的描述。這在有些情況結果就會和我們預期的不同。

原理

詳細查看兩家的 doc,在 SQLAlchemy 對 first() 函數這麼說:

Return the first result of this Query or None if the result doesn’t contain any row.

first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present).

意思是說,他的 first 函數是在 SQL 中增加 LIMIT 1 。

那回頭來看 GORM 呢?

Get the first record ordered by primary key

就這麼簡單一句話XD。如果使用 GORM 的 First,他預設會對 pk 做 order 再取 LIMIT 1。

結論

那如果要在 GORM 達到一開始一樣的 SQL 要怎麼做呢?

db.Order("date desc").Limit(1).Find(&testScore)

這樣就可以啦!

相關文章

用 ForwardRef 解決在 Angular 中遇到的 bug
Python 好慢!datetime 處理優化
發生 Name or service not known?手動設定 Linux DNS 吧!

參考資料

https://docs.sqlalchemy.org/en/14/orm/query.html#sqlalchemy.orm.Query.first
https://gorm.io/docs/query.html

Continue reading
Share:
Angular•那些踩過的坑

用 ForwardRef 解決在 Angular 中遇到的 bug

2021-02-27 by J No Comments

因職位轉換為全端,所以重新學習新的前端框架 angular。公司前端架構目前是 angular js 和 angular 混雜使用,雖然短期內可以順利運作,但長期還是得全部轉換至 angular 才好維護。剛好轉換的工作就讓我這 angular 菜鳥來練練手啦!

這次遇到的 Bug 如下,這是 code base 中已經寫好的 angular directive

@Directive({
  selector: '[datePicker]',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: DatePickerDirective,
      multi: true,
    },
  ],
})
export class DatePickerDirective implements OnInit, ControlValueAccessor, OnChanges {
  @Input() .....

簡單來說他把 jQuery 的 date picker 套件包成 directive,並宣告成 NG_VALUE_ACCESSOR,這樣就能使用 ngModel 來做綁定

<input type="text"
       datePicker  
       [(ngModel)]="asOfDate"
       class="form-control form-date">                                                

但實際測試,發現點擊 input 時 date picker 根本不會出現,為了確定 directive 有效,我在 ngOnInit 的部分加了 log

...
ngOnInit(): void {
  console.log("date-picker work!");
...
}

發現這一行根本不會跑!非常的奇怪,由於同一份檔案還有其他類似包裝 jQuery 的 directive,觀察了一下,另一個用過且確定可以動的 directive 並沒有把他宣告成 NG_VALUE_ACCESSOR,看來這個可能是鬼,於是把他註解掉

@Directive({
  selector: '[datePicker]',
  //providers: [
  //  {
  //    provide: NG_VALUE_ACCESSOR,
  //    useExisting: DatePickerDirective,
  //    multi: true,
  //  },
  ],
})
export class DatePickerDirective implements OnInit, ControlValueAccessor, OnChanges {
  @Input() .....

再試一次,date picker 可以正常出現!但日期卻無法綁定,這合理,因為我們拔掉了 NG_VALUE_ACCESSOR。

解法是,在 useExisting 參數使用 fowardRef 來傳遞 class 實體,而不直接傳 class 進去,如下

@Directive({
  selector: '[datePicker]',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => DatePickerDirective),
      multi: true,
    },
  ],
})
export class DatePickerDirective implements OnInit, ControlValueAccessor, OnChanges {
  @Input() .....

主因是我們在 decorator 裡面引用 DatePickerDirective 時,他順序還在後面沒有宣告到,可能因此導致 angular 出錯,轉變成我們觀察到的現象: directive 根本沒有執行。

但 angular 框架規定要把 NG_VALUE_ACCESSOR 相關的定義放在 decorator 裡面的 providers,此時只好使用 forwardRef 函數作為中介,讓他先取到 forwardRef 函數實體,之後 angular 內部要使用時就可以透過它回傳已經走過宣告的 DatePickerDirective class 實體,如此即能解決宣告順序的問題。

參考資料

[Angular 大師之路] Day 08 – 自訂表單控制項
Forward references in Angular

Continue reading
Share:

About me

author j

J

雖然大學唸的是生物,但持著興趣與熱情自學,畢業後轉戰硬體工程師,與宅宅工程師們一起過著沒日沒夜的生活。之後憑著一股傻勁與朋友創業,再度轉戰軟體工程師,一手扛起前後端、雙平台 app 開發,過程中雖跌跌撞撞,卻也累計不少經驗。

可惜不是那 1% 的成功人士,於是加入其他成功人士的新創公司,專職開發後端。沒想到卻在採前人坑的過程中,拓寬了眼界,得到了深層的領悟。...more

Categories

  • Angular (5)
  • Arduino (5)
    • ESP32 (2)
    • Raspberry Pi Pico (3)
  • AWS (15)
  • Blockchain (11)
  • Deep Learning (16)
    • LLM (2)
    • Stable Diffusion (9)
  • DevOps (22)
  • Frontend (6)
  • Golang (1)
  • Kafka (2)
  • Python (13)
  • Raspberry Pi (32)
    • Banana Pi (3)
    • Jetson Nano (2)
    • Odroid HC4 (4)
    • Rock Pi (6)
  • RetroArch (2)
  • ROS (2)
  • Wordpress (10)
  • 健身 (1)
  • 創客計畫 (15)
    • AI 神經網路自走車 (8)
    • 智慧家居 (7)
  • 好物推薦 (1)
  • 旅行 (2)
    • 峇里島 (2)
  • 說人話的名詞解釋 (3)
  • 那些踩過的坑 (8)
  • 開發哲學 (3)
  • 閱讀筆記 (4)
  • 面試策略 (2)

© 2023 copyright KodingWork  All rights reserved