Question

I am trying to package tweepy in a subdirectory. But I can't get the imports working.

This is the case:

import socialmedia
import tweepy
import logging


# This file is in socialmedia / twitter / __init__.py
# Tweepy is located in socialmedia / twitter / tweepy / __init__.py

# I am getting this error: 
"""
Traceback (most recent call last):
  File "/home/samos/workspace/socialmedia-api/src/test/test.py", line 1, in <module>
    from socialmedia.twitter import TwitterAPI
  File "/home/samos/workspace/socialmedia-api/src/socialmedia/twitter/__init__.py", line 5, in <module>
    from socialmedia.twitter import tweepy
  File "/home/samos/workspace/socialmedia-api/src/socialmedia/twitter/tweepy/__init__.py", line 12, in <module>
    from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResult, ModelFactory
ImportError: No module named tweepy.models
"""

I already tried not using the init.py and using twitter.py, so this doesn't seem to be the problem. It also seems that the import of tweepy is working, but the imports inside tweepy are not working well.

Was it helpful?

Solution

Looks like tweepy expects to be on the Python path--it tries to load tweepy.models. However, since you put tweepy in a subdirectory, the models module is now located at socialmedia.twitter.tweepy.models.

You either have to add socialmedia/twitter/ to the Python path, or you have to change tweepy's imports to compensate for the new package structure. Neither solution is great. The former introduces a special configuration that must be set. The latter will require you to fix the imports any time the tweepy code is updated (because the updated code will contain the original tweepy.whatever imports). This is why it is generally not a good idea to move packages around like you're doing. Instead, just install it as normal (run setup.py or easy_install, or whatever method you prefer) and then in the code that uses the package just import it.

Unless you absolutely must move have the directory structure you describe, I would just install packages normally. You're fighting an uphill battle to do otherwise. Otherwise,

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top