Alex L
Alex L

Reputation: 8925

Import a class variable from another module

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?

Upvotes: 17

Views: 26223

Answers (3)

Manish
Manish

Reputation: 531

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

Upvotes: 1

icktoofay
icktoofay

Reputation: 129001

variable = __import__('module').class.variable 

Upvotes: 15

jsbueno
jsbueno

Reputation: 110263

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.

Upvotes: 10

Related Questions