1

I was studying python import machinery with the official document. I wanted to test what I learned. So I built a basic package and a module which look like as below

pkg
├─── __init__.py # (empty file)
└─── md.py

I instantiated an interactive python shell at the directory where pkg is located. I could import pkg with no error(import pkg). But when I tried to access md module which I thought included in pkg, It gave me an error.

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

I think I was somehow wrong in understanding how import works in python, but I have no clue.

  • 1
    See my explanation here: http://stackoverflow.com/a/41468481/3642398. tldr: only variables functions and classes defined in your `__init__.py` will be directly accessible when you import a package. Try `from pkg import md`. – elethan Jan 16 '17 at 03:04
  • @elethan Thanks a lot. Now it works fine. Could I ask you just one more question? When I'm importing `scrapy` package (scrapy version 1.1 in python 2.7 on ubuntu linux) I get to be able to access `scrapy.http`, even though it doesn't seem to be explicitly defined in `__init__.py` file of `scrapy` pacakge. I guess `from scrapy.http import Request, FormRequest` line of that file did the job somehow, but I am not entirely sure. –  Jan 16 '17 at 04:13
  • 1
    Yes, I think you are exactly right: when `Request` and `FormRequest` get import from `scrapy.http`, this adds the `http` subpackage to the namespace of `scrapy`. This won't always happen though, so generally if you know something is a submodule or subpackage, you should explicitly import it - `from pkg import md` - or explicitly import whatever you want to use from the subpackage/submodule - `from pkg.md import SomeClass`. Also, if the solution I linked was helpful to you, don't forget to upvote ;) – elethan Jan 16 '17 at 18:42
  • Possible duplicate of [sklearn doesn't have attribute 'datasets'](http://stackoverflow.com/questions/41467570/sklearn-doesnt-have-attribute-datasets) – mzjn Feb 16 '17 at 20:09

0 Answers0