简体   繁体   中英

Why do I always get type info printed when using python fire?

I have a simple test python-fire cli program in python 2.7.15

import fire

class Math:
    def add(x, y):
      """add"""
      return x + y

    def multiply(x, y):
      """multiply"""
      return x * y

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

If I write

python-fire-test.py

the response from the program is

Type:        instance
String form: <__main__.Math instance at 0x0000000003CE89C8>

Usage:       python-fire-test.py
             python-fire-test.py add
             python-fire-test.py multiply

However I don't expect to see

Type:        instance
String form: <__main__.Math instance at 0x0000000003CE89C8>

printed at the top. Can I stop this behaviour?

This behavior has been replaced with cleaner output in Python Fire v0.2.0. Upgrade Fire with pip install -U fire to get the latest version.

You have two problems in your code. The more immediate one as to why you are actually getting the result you are seeing is because of a misuse of the library.

The result you are getting is in fact simply the result of fire.Fire(Math) , which is a representation of the instance object you are getting from fire.Fire(Math) .

Your utilization should in fact be this:

(venv) ➜ python python-fire-test.py multiply 5 5
25
(venv) ➜ python python-fire-test.py add 5 5     
10

However, there is another problem you are facing that won't get you that result either now. In your code you are creating a class called Math . In your instance methods ( add , multiply ), you are going to face issues when you try to use it, due to the fact you are not passing the necessary explicit reference for the instance itself self . So, your code should now be:

import fire

class Math:
    def add(self, x, y):
      """add"""
      return x + y

    def multiply(self, x, y):
      """multiply"""
      return x * y

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

A little further down in the README for the lib you are using the utilization is shown as:

python calculator.py double 10  # 20
python calculator.py double --number=15  # 30

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM