简体   繁体   中英

How do I implement Duck Typing when typing function?

I've got a function:

def optimize_image(image) -> BytesIO:
    """
    Takes image and returns it's compressed version if necessary
    """
    pass

How do I duck type input and output as objects which implement certain methods (for example, open() ) instead of specifying certain object types like BytesIO?

I found creating an abstract class for that purpose to be the best solution. Something like this:

from abc import ABCMeta, abstractmethod

class Openable():
    __metaclass__=ABCMeta

    @abstractmethod
    def open():
    """Open object"""

def optimize_image(image: Openable) -> Openable:
    """
    Takes image and returns it's compressed version if necessary
    """
    pass

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