Home > Net >  declaring classes from imported modules in python
declaring classes from imported modules in python

Time:12-24

In python you have to use

import <module>

to import a file with classes.

Imagine the module contains multiple classes

And now I want to declare an object

x = module.object1Name(parameter1,parmeter2)

How can I declare that object without having to access it through module? (So like this below)

x = object1Name(parameter1,parameter2)

Also I do not want to use the following because it would mean I would have to do that for every class.

from <module> import <objectName>

CodePudding user response:

You can combine multiple from <module> import <objectName> statements with commas and parentheses.

For example:

from <module> import <objectNameA>, <objectNameB>

or

from <module> import (<objectNameA>, <objectNameB>)

The latter will work across multiple lines (ref).

Using import * from <module> (import everything from <module>) is bad because it risks overriding functions, classes, and variables from other modules, and it violates the Zen of Python "better to be explicit" value.

CodePudding user response:

You can you the following statement, that will import everything from the module:

from <module> import *

But it is not a good practice, for some reasons:

  • Your code must import only what you uses.
  • The zen of python says "explicit is better than implicit", so if you want to use something, you need to import it explicitly.
  • Improve the readability of your code.

I suggest to use the explicit imports in what you want to use.

from <module> import <object1>, <object2>

Or, like below:

from <module> import (
    <object1>,
    <object2>,
    <object3>,
    <object4>
)
  • Related