0

I have created verbose_on (it shows output if used) and verbose_off fuction. In verbose_on(fn), fn is another function.

helper.py

import os
import sys
import io
def verbose_on(fn):
    sys.stdout = io.StringIO()
    fn()
    output = sys.stdout.getvalue()
    sys.stdout = sys.__stdout__
    print(output)


def verbose_off(fn):
    sys.stdout = io.StringIO()
    fn()
    sys.stdout = sys.__stdout__
    print('Task Completed.')

/dev.py

In sample function there are some commands, whose output need to be showed in test function if verbose is on.

def sample(flag2):
    print('tests are running')
    # another commands running

/main.py

It has test function which has two flags, one to activate verbose and another flag which is needed to pass with sample. Check helper.verbose_off(sample) in test function, it is passing sample which will be converted to function in verbose_on method(fn(), i.e. sample())

from dev import sample
from helper import verbose_on, verbose_off
def test(verbose, flag2):
    if verbose:
        print('Verbose mode = On.')
        helper.verbose_on(sample)
    else:
        print('Verbose mode = Off')
        helper.verbose_off(sample)

But it is needed that flag2 shoud be pass with sample inside test function, something like this : helper.verbose_on(sample(flag2)). Any suggestions will be appreciated. Thank you in advance.

8
  • 4
    Sounds like you think of a partial function? Commented Jul 27, 2022 at 16:09
  • 1
    use lambda x: sample(flag) Commented Jul 27, 2022 at 16:10
  • 1
    @VladimirVilimaitis it is something similar. Commented Jul 27, 2022 at 16:12
  • 1
    @NIKHILPIMPARE another user already added. Commented Jul 27, 2022 at 16:17
  • 1
    Don't forget the function itself, i.e. def verbose_on(fn, *args, **kwargs), that calls fn(*args, **kwargs), and you call verbose_on(sample, flag2) Commented Jul 27, 2022 at 16:56

1 Answer 1

2

Use lambda functions:

def test(verbose, flag2):
    if verbose:
        print('Verbose mode = On.')
        helper.verbose_on(lambda: sample(flag2))

or functools.partial:

def test(verbose, flag2):
    if verbose:
        print('Verbose mode = On.')
        helper.verbose_on(functools.partial(sample, flag2))
Sign up to request clarification or add additional context in comments.

2 Comments

if we use functools.partial then do we need to do changes in verbose_on method?
No, functools.partial will return a callable object, which will be called by the fn() statement in verbose_on/off. Even after the change, only one argument is passed to verbose_on/off.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.