0

I have a function where I'm searching for regex patterns in sentences and file paths. To do this, I need to chunk the text so that it evaluates full words, not individual characters.

def print_word_and_match_fragment(text):

    word_list = text.split('\\') if '\\' in text else text.split()

    patterns = re.compile(r'^[a,A][b,B]{2,3}$')
    d = dict()
    for i in word_list: # Does something 

To me, it doesn't seem right that I have to make a local ternary variable within the function to do what I need it to do

Why can't it be:

def print_word_and_match_fragment(text = text.split('\\') if '\\' in text else text.split() ):

    

    patterns = re.compile(r'^[a,A][b,B]{2,3}$')
    d = dict()
    for i in text: # Does something 

Is there a way I could just call the ternary as the function parameter or at least something that's equivalent? It doesn't have to be a ternary. Some vague ideas I have was maybe using **args or :=.

  • 3
    Because default function values are evaluated when you *define* the function, not when you call it. – chepner Nov 13 '22 at 02:15
  • (Also, I think you mean *temporary*, not ternary.) – chepner Nov 13 '22 at 02:15
  • 2
    `a if b else c` is indeed a ternary expression, but the variable is not a ternary, it's just the list you get back from one of the two `split` calls. – Blckknght Nov 13 '22 at 02:16
  • Also, there's a case to be made that the caller should be responsible for splitting the string on the appropriate character in order to provide a list of words to as the argument. – chepner Nov 13 '22 at 02:28

1 Answers1

0

This will work for the default argument, but it will only be evaluated once when the function definition is read
also see "Least Astonishment" and the Mutable Default Argument

Instead, you may be able to use re.findall() or re.finditer() to optionally include // and \b as a word boundary

ti7
  • 16,375
  • 6
  • 40
  • 68