What's the best practice for handling single-value tuples in Python?

前端 未结 9 1962
长发绾君心
长发绾君心 2021-02-19 05:44

I am using a 3rd party library function which reads a set of keywords from a file, and is supposed to return a tuple of values. It does this correctly as long as there are at le

9条回答
  •  春和景丽
    2021-02-19 06:01

    There's always monkeypatching!

    # Store a reference to the real library function
    really_get_keywords = library.get_keywords
    
    # Define out patched version of the function, which uses the real
    # version above, adjusting its return value as necessary
    def patched_get_keywords():
        """Make sure we always get a tuple of keywords."""
        result = really_get_keywords()
        return result if isinstance(result, tuple) else (result,)
    
    # Install the patched version
    library.get_keywords = patched_get_keywords
    

    NOTE: This code might burn down your house and sleep with your wife.

提交回复
热议问题