0

I am using two if conditions in the below code snippet. disable_env value can be passed as a parameter to a function or as an environment variable. Is there a more efficient way to do this in Python using a single if statement?

def func(disable_env=False):
  if os.environ.get("DISABLE_ENV"):
     disable_env=True
  if not disable_env: 
     print("something")

3
  • 3
    Single if statement won't make this more efficient. It will however make it less readable. If you really want it will be somethong like if not (disable_env := os.environ.get("DISABLE_ENV")): print("something") using Assignment Expressions Commented Jul 24, 2022 at 5:49
  • 1
    if 'DISABLE_ENV' not in os.environ and not disable_env: print('something') Commented Jul 24, 2022 at 5:59
  • print("something" if not os.environ.get("DISABLE_ENV") else "") Commented Jul 24, 2022 at 6:06

1 Answer 1

1
def func(disable_env=False):    
    disable_env = os.environ.get("DISABLE_ENV", disable_env)

should do the trick.

Sign up to request clarification or add additional context in comments.

Comments

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.