1

I experienced a problem using the 'import module' instead of the 'from module import ...' syntax. This clearly shows that my understanding of loading modules is not sufficient. As far as I find elsewhere, this difference is mainly a style issue, but this does not explains the following situation.

I installed ase using

sudo apt install python3-ase

I tried the following:

import ase
ase.io.read

which outputs

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'ase' has no attribute 'io'

However, when trying

from ase.io import read
read

or - also possible -

from ase.io import read
import ase
ase.io.read

I get the output

<function read at 0x7f33dc721730>

The latter is the desired result as I want to use the ase.io.read function to read a .cif file.

More about the origin of the problem is shown in the following python session:

import sys
import ase
sys.modules['ase']

module 'ase' from '/home/vanbeverj/Programs/anaconda3/envs/abienv/lib/python3.6/site-packages/ase/init.py'

dir(ase)

['Atom', 'Atoms', 'LooseVersion', 'all', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec', 'version', 'ase', 'atom', 'atoms', 'calculators', 'cell', 'constraints', 'data', 'dft', 'formula', 'geometry', 'np', 'parallel', 'symbols', 'sys', 'transport', 'units', 'utils']

from ase.io import read
dir(ase)

['Atom', 'Atoms', 'LooseVersion', 'all', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec', 'version', 'ase', 'atom', 'atoms', 'calculators', 'cell', 'constraints', 'data', 'dft', 'formula', 'geometry', 'io', 'np', 'parallel', 'symbols', 'sys', 'transport', 'units', 'utils']

The 'dir(ase)' commands have clearly different outputs. What happens with e.g. the io submodule? Can someone explains me what is going on under the hood?

Josja
  • 131
  • 7

2 Answers2

2

It's up to each package whether to expose an imported submodule as an attribute, or whether to import the submodule at all.

os, for example, does import and expose os.path.

In your case, ase does not expose the io submodule as an attribute of ase. (Whether io was imported is another matter; you could check sys.modules.)

chepner
  • 497,756
  • 71
  • 530
  • 681
1

I think it seems like tkinter. In tkinter,if we want to use ttk,we must use

import tkinter
from tkinter import ttk 

if we use

import tkinter

.......
btn = tkinter.ttk.Button(xxxxxx)

Then it will show AttributeError: module 'tkinter' has no attribute 'ttk'.

You can see the ase module source.In ase > __init__.py file,import ase means that import all of class or function in __init__.py.

from ase import io,maybe it means that it will import the io module(io is a independent .py file) in ase folder

jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49