google / google/python-fire

Avoid calling __init__ for classmethod/staticmethod

未關閉
#450 1 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視
主要語言
Python
星號
28.2k
分支
1.5k
PR 合併指標
30 天內沒有已合併 PR

描述

Suppose we want a CLI that is similar to `git` in the sense that we must first call `init` before interacting with the repo. For this, we aim for the following (simplified/partially implemented) class, which is intentionally similar to `GitPython`s `Repo` class (see [here](https://gitpython.readthedocs.io/en/stable/tutorial.html)):

```python
from pathlib import Path
import fire

class SomethingLikeGit:

dirname = ".something_like_git"

@classmethod
def init(cls, path=None):
path = Path(path or Path.cwd())
path = path / cls.dirname
print("Initializing at", path)
path.mkdir()
...
print("Done.")

def __init__(self, path=None):
path = Path(path or Path.cwd())
for parent in (path, *path.parents):
self.path = parent / self.dirname
if self.path.exists():
break
else:
raise FileNotFoundError(path)

...

if __name__ == "__main__":
fire.Fire(SomethingLikeGit)
```

When we run the command `python something_like_git.py init`, it first tries to instantiate the class via `__init__`, which fails (FileNotFoundError) since it must first create the directory via `init`.
I think it makes generally more sense if Fire would call classmethods/staticmethods directly on the class without trying to instantiate it. This is usually also how class/static methods are used in a programmatic way (e.g. for [`git.Repo`](https://gitpython.readthedocs.io/en/stable/tutorial.html)).

Note that the fix for #113 does not resolve this issue. This is because the `path` argument for `__init__` is (intentionally) optional, so Fire thinks it can call `__init__` first. If `path` wasn't optional, it would behave as wanted: `init` would be called without first calling `__init__`.

Anyway, thanks for your great work!

貢獻指南

開啟貢獻指南

研究方向

從範例中所示的 Fire 入口 `fire.Fire(SomethingLikeGit)` 開始,追蹤 `init`、`__init__`、類別方法和靜態方法是如何被分派的。在不存在 `.something_like_git` 目錄的情況下重現 `python something_like_git.py init`;當 `init` 可以在不呼叫 `__init__` 的情況下執行,同時一般執行個體命令保留目前的初始化行為時,即表示完成。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
cli
Issue 類型
功能
難度
4/5
預估耗時
3-5 天
活躍度
停滯
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。