krock1516
krock1516

Reputation: 461

Better way to check variable to avoid multiple conditions for multiple variables

I have below example code where it has three variable defined job_Name out_File err_File.

Now I'm looking to remove this from print statement if any of the variable or all the variables either empty ot not defined

job_Name = "Test"
out_File = "/tmp/123"
err_File = "/tmp/321"

print("Job Name {0},Output {1}, Error {2}".format(job_Name,out_File,err_File))

ie: if job_Name is empty it should print :

Output  Error
/tmp/123 /tmp/321

Let suppose out_File and err_File not defined it should only print job_Name.

Job Name 
Test

This can be done with chain conditions if else etc.. but looking if that can be avoid as we have multiple such variables and achieved with some smarter or other elegant way.

Upvotes: 0

Views: 85

Answers (3)

Ghostkeeper
Ghostkeeper

Reputation: 3050

Maybe this is a solution for you, but it'll depend on where those variables come from:

error_data = {
    "Job Name": "Test",
    "Output": "/tmp/123",
    "Error": "/tmp/321"
}
line = []
for description, value in error_data.items():
    if(value):
        line.append("{description} {value}".format(description=description, value=value))

print(",".join(line))

Upvotes: 1

Kostas Charitidis
Kostas Charitidis

Reputation: 3103

A little extended but does the trick:

job_Name = "Test"
out_File = "/tmp/123"
err_File = "/tmp/321"

headers = ''
output = ''
if job_Name:
    headers += 'Job Name\t'
if out_File:
    headers += 'Output\t'
if err_File:
    headers += 'Error\t'

for val in [job_Name, out_File, err_File]:
    if val:
        output += val + '\t'

print(headers)
print(output)

and another approach if your variables have the desired name to print could be this:

def retrieve_name(var):
    # prints the given variable's name
    import inspect
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()
    return [var_name for var_name, var_val in callers_local_vars if var_val is var]


job_Name = "Test"
out_File = "/tmp/123"
err_File = "/tmp/321"

headers = ''
output = ''

for val in [job_Name, out_File, err_File]:
    if val:
        headers += str(retrieve_name(val)[0]) + '\t'
        output += val + '\t'

print(headers)
print(output)

Upvotes: 1

SpghttCd
SpghttCd

Reputation: 10860

Perhaps you could do

print(f"{'Job Name' + job_Name + ', ' if job_Name else ''}{'Output' + out_File + ', ' if out_File else ''}{'Error' + err_File + ', ' if err_File else ''}")

Upvotes: 0

Related Questions