Python3 - How do I import a class from another file

R.Wieser address at not.available
Sun Dec 8 13:18:05 EST 2019


Peter,

>> "from file import function" works, but fails when I try to do the same
>> with a class.
>
> Are you sure? It should behave the same for any name in the module.

I am.

At least, that is what the error said: "cannot import 'classname' from 
'filename' "

But as it turns out the problem is not the importing, but that my importing 
of the class also caused my testcode (instanciating the class, calling it 
and deleting the instance afterwards) to run.

... in which I created an instance with the same name as the class. 
Changing the instances name made the error go away (probably something to do 
with the "del instance" in the testcode).

> It's all or nothing, you cannot cherry-pick specific classes or functions.

Shucks.

> You can however protect part of the code with
> 'if __name__ == "__main__": ...':

Thanks.  (Python" also mentioned the above two).

Regards,
Rudy Wieser




More information about the Python-list mailing list