Avoid calling __init__ for classmethod/staticmethod

Aberta
#450 1 comentário 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
4/5
Tempo estimado
3-5 dias
Facilidade para iniciantes
45/100
Tipo de issue
Funcionalidade
Clareza
Razoavelmente clara
Status de atividade
Estagnada
Stack de tecnologia
python
Domínio
cli

Direção de pesquisa

Comece pelo ponto de entrada do Fire mostrado no exemplo, fire.Fire(SomethingLikeGit), e rastreie como init, __init__, métodos de classe e métodos estáticos são despachados. Reproduza python something_like_git.py init sem um diretório .something_like_git existente; está concluído quando init puder ser executado sem invocar __init__, enquanto os comandos comuns de instância mantêm seu comportamento atual de inicialização.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

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 GitPythons Repo class (see here):

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).

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!

Linguagem predominante
Python
Estrelas
28.2k
Forks
1.5k
Métricas de merge de PRs
Nenhum PR com merge em 30d

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de google/python-fire

Todas as issues de google/python-fire

Issues semelhantes

Mais issues de Python

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.