0

Is it possible to put a generator that always returns 'True' in one line? The reason for that being is that it should be a default parameter in a function or is there a way to use these parameters having multiple lines?

This should be the default argument of a function:

def example_function(generator= (def gen():
                                    while True:
                                        yield True)):
                                            print("In my function")

The code with that indentation shows the following syntax error:

def example_function(generator= (def gen():
                                   ^
David
  • 2,926
  • 1
  • 27
  • 61

1 Answers1

1

If I understand correctly that's what you need:

def example_function(generator=None):

   def default_generator():
       while True:
           yield True

  generator = generator or default_generator

There is generally no reason to put things in one line. On the other hand you could also use itertools.repeat(True) to define the default_generator, it would save few lines of code:

import itertools

def example_function(generator=None): 
    generator = generator or itertools.repeat(True)

In general it's a good idea to use x=None for default keyword arguments with default values. You can have a look at why using an object instead of None can be risky (functions are objects too, so this applies here).

cglacet
  • 8,873
  • 4
  • 45
  • 60