Search code examples
pythontextword-wrap

how to indent the following prints


lets say I have someone else's function which does the following:

def print_numbers(N):
    for i in range(N):
        print(i,'- something something')

now without changing the function I would like to call it from outside such that it will be printed with initial indentation (for simplicity lets say \t) as such:

Here are some random numbers:
     0 - something something
     1 - something something
     2 - something something
     3 - something something
     4 - something something

I tried something like this:

print('Here are some random numbers:')
with textwrap.set_indent('\t'):
    print_numbers(5)

But I couldn't find such method.. Is it possible?


Solution

  • You could do this:

    def print_numbers(N):
        for i in range(N):
            print(i,'- something something')
    
    def special_print(*args):
        pf('\t', *args)
    
    pf = print # save reference to original built-in
    print = special_print # override
    print_numbers(5)
    print = pf # reset built-in