python-fire icon indicating copy to clipboard operation
python-fire copied to clipboard

What is the best way to have a "factory method" style?

Open melezhik opened this issue 4 years ago • 5 comments

Right now I ended up with a following approach ( not sure if it the best):

import fire
import foo
import bar

def foo(*args):
  Foo(*args).configure()

def bar(*args):
  Bar(*args).configure()

def dispatch(**args):
  print("arguments passed", args)
  """Factory Method"""
  localizers = {
    "policy": foo,
    "repo": bar,
  }
  return localizers[args["obj_type"]](args)

if __name__ == '__main__':
  fire.Fire(dispatch)

Ideally I would want that Fire method allow me to pass classnames as variable which I define through a command line, something like that:

from ado import * # Repo and Policy classes are defined at libs/ado.py 

if __name__ == '__main__':
  fire.Fire(obj_type)
python script.py --obj_type=Foo

Not sure if it's possible 🤔 ...

melezhik avatar Nov 15 '21 19:11 melezhik

finally I ended with this slightly shorter code, but the question still stands:

import fire

from foo import *
from bar import *

import fire

def dispatch(**args):
  print("arguments passed", args)
  """Factory Method"""
  localizers = {
    "foo": Foo,
    "bar": Bar,
  }
  class_name = localizers[args["obj_type"]]
  obj = class_name(args)
  class_method = getattr(class_name,obj.method)
  class_method(obj)

if __name__ == '__main__':
  fire.Fire(dispatch)
python script.py --obj_type=Repo

melezhik avatar Nov 15 '21 21:11 melezhik

Hi, I think that what you are looking for is just:

from foo import Foo
from bar import Bar

if __name__ == '__main__':
  import fire
  fire.Fire({"foo": Foo, "bar": Bar,})

then, you can call:

python script.py foo <foo args>

or:

python script.py bar <bar args>

PierreGtch avatar Dec 01 '21 16:12 PierreGtch

interesting ... maybe wil give it a try ...

melezhik avatar Dec 01 '21 16:12 melezhik

Ok

a09174079722A avatar Jan 01 '22 03:01 a09174079722A

Ok

a09174079722A avatar Jan 01 '22 03:01 a09174079722A