15

I'm working with the PyFacebook package in Python, and I've seen people mention numerous times that you can write an import statement as follows:

from facebook.djangofb import facebook

However, it does not work. It states that facebook.method_name exists in the facebook module, rather than the djangofb module. I assume I'm importing the facebook.method_name as facebook, not that I'm receiving it from the facebook package itself.

I'm using Python 2.6.

How can I alias facebook.djangofb as facebook?

SirJames
  • 387
  • 8
  • 27
Bialecki
  • 30,061
  • 36
  • 87
  • 109
  • 7
    @qarma: your bounty message makes no sense; it certainly doesn't seem to have any relationship to the question being asked here. – Martijn Pieters Feb 04 '17 at 22:17

3 Answers3

30

This is the proper way to alias a module via import:

import facebook.djangofb as facebook
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
6

From the python 3 documentation (it works the same way in python 2.6, but I found the python 3 documentation explained it clearer):

If the module name is followed by as, then the name following as is bound directly to the imported module.

So your statement should look like:

import facebook.djangofb as facebook

and then facebook.method_name will work.

Also see Can you define aliases for imported modules in Python? for additional aliasing options

rabidang3ls
  • 175
  • 2
  • 8
2
from facebook import djangofb as facebook

If you're looking to import djangofb as facebook, that's how you need to do it.

This way, you can access facebook.djangofb.method_name like facebook.method_name.

That being said, it's more common to give it a non conflicting name, here it would be fb or face. Something that doesn't override the root facebook import.

TankorSmash
  • 12,186
  • 6
  • 68
  • 106