python-fire
python-fire copied to clipboard
What is the best way to have a "factory method" style?
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 🤔 ...
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
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>
interesting ... maybe wil give it a try ...
Ok
Ok