Import a class variable from another module
Asked Answered
B

3

17

I'm trying to import just a variable inside a class from another module:

import module.class.variable 
# ImportError: No module named class.variable

from module.class import variable 
# ImportError: No module named class

from module import class.variable
# SyntaxError: invalid syntax (the . is highlighted)

I can do the following, but I'd prefer to just import the one variable I need.

from module import class as tmp
new_variable_name = tmp.variable
del tmp

Is this possible?

Brecciate answered 6/2, 2012 at 2:46 Comment(0)
S
15
variable = __import__('module').class.variable 
Semmes answered 6/2, 2012 at 2:52 Comment(3)
Am I correct in thinking that this will import the whole module? Equivalent to import module then variable = module.class.variable ?Brecciate
Except that it won't bind any name to the imported module. Which is fine; from module import clazz "imports the whole module" too, in exactly the same way. There's simply no way around this; the class definition can't be guaranteed to make any sense without the rest of the module's context, and similarly for attributes of the class.Audacious
@Alex It will always be imported the whole module (but it depends on your statement what will be available in your scripts scope). from x1 import x2 will load x1 and then look where to find x2, either in the scope of x2 or as a sub-package.Implausible
E
10

You can't do that - the import statement can only bring elements from modules or submodules - class attributes, although addressable with the same dot syntax that is used for sub-module access, can't be individually imported.

What you can do is:

from mymodule import myclass
myvar = myclass.myvar
del myclass

Either way, whenever one does use the from module import anything syntax, the whole module is read and processed.The exception is

from module.submodule import submodule

, where, if thesubmodule itself does not require the whole module, only the submodule is processed.

(So, even onmy workaround above , mymodule is read, and executed - it is not made accessible in the global namespace where the import statement is made, but it will be visible, with all its components, in the sys.modules dictionary.

Eugeniusz answered 6/2, 2012 at 3:15 Comment(1)
Your workaround looks remarkably similar to my workaround! Thanks for the explanationBrecciate
M
1

Follow these two steps

  1. Import the class from the module

    from Module import Class

  2. Assign new variables to the existing variables from the class

    var1=Class.var1

    var2=Class.var2

Marci answered 23/5, 2021 at 11:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.