简体   繁体   中英

ImportError: cannot import X from the file that has if __name__ == “__main__”. Any solutions without delete if __name__ == “__main__”?

I have 2 files n1711_001_insilico and n1711_002_insilico in the same folder. I want two variables ( mzdf which is <class 'pandas.core.frame.DataFrame'> , and charge is 'int' ) from the first file so I do import at the top of the second file:

import numpy as np
import pandas as pd
from n1711_001_insilico import mzdf, charge

I got ImportError: cannot import name mzdf (as well as for charge ). In the first file, I explicitly return both mzdf and charge from the function and call them like this:

if __name__ == "__main__":
    mzdf, charge = CALC(peptides_report, aa_dict, charge_from=1, charge_to=6)

Update: from the comment I now know the issue comes from if __name__ == "__main__": in the first file. Any ways that I can fix this without deleting if __name__ == "__main__" ?

In the file you are trying to import, you have this statement:

if __name__ == "__main__":
    mzdf, charge = CALC(peptides_report, aa_dict, charge_from=1, charge_to=6)

This means that only if the file is directly executed in the command line, for example with python n1711_001_insilico.py will the command CALC actually run and be executed, and this is the function that is setting the two variables mzdf and charge .

In other words, only when you run the file directly with python n1711_001_insilico.py do these two variables exist, when you import it, Python will not run that function.

This is by design; once you import the file, the variable __name__ points to the name of the file, so the condition fails.

Now, to solve this problem you will have to run the CALC function when you import the file, and get your own copy of the result:

import numpy as np
import pandas as pd
from n1711_001_insilico import peptides_report, aa_dict, CALC

mzdf, charge = CALC(peptides_report, aa_dict, charge_form=1, charge_to=6)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM