Is there a way to check whether function output is assigned to a variable in Python?

前端 未结 7 909
[愿得一人]
[愿得一人] 2021-01-22 14:31

In Python, I\'d like to write a function that would pretty-print its results to the console if called by itself (mostly for use interactively or for debugging). For the purpose

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-22 15:02

    There is no way to do this, at least not with the normal syntax procedures, because the function call and the assignment are completely independent operations, which have no awareness of each other.

    The simplest workaround I can see for this is to pass a flag as an arg to your check_status function, and deal with it accordingly.

    def check_status(return_dict=False) :
        if return_dict :
            # Return stuff here.
        # Pretty Print stuff here.
    

    And then...

    check_status() # Pretty print
    not_robot_stat = check_status(True) # Get the dict.
    

    EDIT: I assumed you'd be pretty printing more often than you'd assign. If that's not the case, interchange the default value and the value you pass in.

提交回复
热议问题