4

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
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Shengxin Huang
  • 647
  • 1
  • 11
  • 25
  • 1
    usage of `.` or `..` are nothing but file accessors. Like how we use `cd ..` or `vi .hello.py` So, basically single dot `.` means current directory file, while double dot `..` means one level up in directory. – Om Sao May 16 '19 at 06:11
  • 1
    Possible duplicate of [How to do relative imports in Python?](https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python) – Devesh Kumar Singh May 16 '19 at 06:16
  • If any of the answers solved your question, it's good practice to upvote them and accept the best one. The latter also grants you a small rep bonus :) – Alec May 16 '19 at 06:25

2 Answers2

2

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!

Justin
  • 1,006
  • 12
  • 25
0

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.

Alec
  • 8,529
  • 8
  • 37
  • 63