HernanProust
HernanProust

Reputation: 11

How to synthesize this python function

I am trying to make a code more compact. I think there is a part that can be nicely reduced but am not sure how to do it. I put a comment inside the code copied below for you to find it fast.

The code is the next one:

def change_to_mop_gen(infile, namedir="",charge=0, gnorm=None, separate=True, hamiltonian="PM6", calctype="opt", multiplicity="singlet", eps=None, cycles=None):
#armado de la salida
    if calctype=="thermo(298,298,0)":
        calctype1="thermo"
    else: 
        calctype1=calctype
    outfile=infile.split(".")[0] + "-" + calctype1 + "-" + hamiltonian

#~ here comes the set of if / else sentences i think could be reduced

    if gnorm !=None:
        gnorm="gnorm=" + str(gnorm)
    else:
        gnorm= " "
    if cycles!=None:
        cycles="cycles="+str(cycles)
    else:
        cycles=""
    if separate==True:
        outfile=outfile + "_*.mop"
    else:
        outfile=outfile + ".mop"
    if eps !=None:
        eps="eps=" + str(eps)
    else:
        eps = ""  

    #~here it ends

    keywords = "-xk '%s  %s %s %s %s %s charge=%i'"%(cycles, hamiltonian, calctype, multiplicity, eps, gnorm, charge)
    #change directory of outfile
    if namedir!="":
        outfile= namedir + "/" + outfile
    return change_format(infile,outfile, keywords)

Any help would be good.

Upvotes: 0

Views: 185

Answers (1)

JoshKopen
JoshKopen

Reputation: 960

I cleaned up and corrected your code here:

gnorm= ("gnorm=" + str(gnorm)) if gnorm is not None else ""
cycles="cycles="+str(cycles) if cycles is not None else ""
outfile=(outfile + "_*.mop") if separate else (outfile + ".mop")
eps=("eps=" + str(eps)) if eps is not None else ""

This is how to write your methods shorthand. Also you should never evaluate that a boolean is == to true, the boolean itself is the condition. Also you do is or is not none not equals evaluations.

Upvotes: 1

Related Questions