0
def extraction(content: str,  channels: List[Color]=[Color.Red]):
  pass

The second argument channels is a List of Color. However, what about if I also want to allow the possibility of channels being a str argument? In that case, it becomes:

def extraction(content: str,  channels: str=None):
      pass

Is it possible to combine the two definitions into one function definition?

marlon
  • 6,029
  • 8
  • 42
  • 76
  • Optional is your friend. Also note that Python typing is completely optional. Nothing prevents you from passing whatever types into that function. – Norrius Feb 04 '21 at 22:56
  • If you want to say that `channels` can be a `List[color]` or a `str`, that would be `Union[List[Color], str]`. You can't have different defaults based on type though. You'd have to do something like default to `None`, then decide through some other means what value it should have. Also note, you should [usually not have a mutable default argument](https://stackoverflow.com/questions/1367883/methods-default-parameter-values-are-evaluated-once). It won't always cause problems, but it opens the door up to certain bugs. – Carcigenicate Feb 04 '21 at 22:58
  • @Carcigenicate, if Union is used, then should I use instanceOf to check whether it is a List or str in the function body? – marlon Feb 04 '21 at 23:01
  • You could yes. Runtime checking of types is often a smell though. If the function requires that different of types for its second parameter, it may make more sense to define different functions altogether, then have one defer to the other, or a third helper function. – Carcigenicate Feb 04 '21 at 23:06
  • I see. But I do often see instaneOf is used in others' code. Is that right? Isn't this the best use case of it? – marlon Feb 04 '21 at 23:10
  • It's common to use for "high level" convenience functions meant to make code easy to use. It suggests though that a function may be doing too much. What happens if you ever need to add another possible type in the future? You'll need to come back and modify your existing code to handle it. I've found it to be cleaner to just have a separate `fromSomeType` and `fromSomeOtherType` style functions, where each function is only handling a narrow task. – Carcigenicate Feb 04 '21 at 23:24

2 Answers2

2
def extraction(content: str,  channels) :
    if type (channels) is str :
        print ('channels is a string.')
    if type (channels) is list :
        print ('channels is a list.')

extraction ('testing', ['one, two three'])
bashBedlam
  • 1,402
  • 1
  • 7
  • 11
1

To better implement this do the following:

from typing import Union

def extraction(content: str,  channels: Union[str, List[Color]]) :
    if type (channels) is str :
        print ('channels is a string.')
    if type (channels) is list :
        print ('channels is a list.')

extraction ('testing', ['one, two three'])