Shengxin Huang
Shengxin Huang

Reputation: 707

What does a dot denote in an import statement?

Could anyone please explains what from .object import object means?

I know that everything extends object just like in Java.But what does .object means?

I saw this piece of code in the source code in psycopg2:

from .object import object

class cursor(object):
    pass

Upvotes: 4

Views: 3623

Answers (2)

Justin
Justin

Reputation: 1031

That's the new syntax for explicit relative imports. It means import from the current package.

Without the ., if you had a file _object.py for some indecipherable reason next to your main script, object would break. With the ., it ensures it gets its own module.

The thing that defines what a "current package" is that it should say from where the importing package is. It basically means the current namespace or package directory.

Hope this helps!

Upvotes: 2

Alec
Alec

Reputation: 9575

From the docs:

One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod. If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod. The specification for relative imports is contained within PEP 328.

The dot is basically telling the program to search in the current directory before looking at the files in your python path. If object exists in both the current directory and your python path, only the one from the former will be imported.

Upvotes: 0

Related Questions