1

I was looking at the pandas source code here, and I found the following statement a little bit weird:

from pandas._libs import NaT, groupby as libgroupby, iNaT, lib, reduction

It seems that it imported Nat and groupby, which are two libraries, as multiple modules (libgroupby, iNaT, lib, reduction).

  1. I went to the pandas._libs library here, but I didn't find any model with name NaT. There is indeed a groupby.pyx, which I assume is the groupby library?

  2. Can the number of imported libraries be less than the imported modules? How does that work? From my past understanding, we can do import a as b, but we cannot do import a as b, c.

2
  • 2
    The second part of your question is answered here Commented Feb 5, 2019 at 9:51
  • 1
    @DavidW Thanks for pointing me to that direction! Commented Feb 5, 2019 at 10:57

1 Answer 1

2

from pandas._libs it actually imported 5 method/class/module:

  1. NaT,
  2. grouby as libgroupy (so in your script you will now use libgroupy)
  3. iNaT
  4. lib
  5. reduction

Now NaT and iNaT indeed doesn't exists in the _libs folder, but it won't give an import error because they are imported from somewhere else in __init__.py of _libs.
__init__.py of a package implicitly executes whenever something is imported from that package or it's subpackages.
So the __init__.py inside _libs will execute, where NaT, iNaT etc. is imported from package .tslibs hence making them available for import from .libs package too.
Now if you will look for NaT or iNaT in the .tslibs folder you will won't find it, but if you will look at the __init__.py of .tslibs you will see here NaT and iNaT is imported from .nattype, so if you look inside that file this time you will find the definition of NaT and iNaT in there.

You can take a look at the docs for better explanation


You can import it like this and then it might be easier for you to understand whats going on:

from pandas._libs import NaT, iNaT, lib, reduction, groupby as libgroupby

This import will do exactly the same as what the import statement in your question does.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Very precise answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.