0

My apologies for a seemingly easy question, I'm new to using classes in Python.

I am using Pycharm and my folder structure looks as follows:

enter image description here

The folder constant-contact-python-wrapper has a few classes defined under __init.py__ and restful_lib.py (I got this library from github). I would like to use these classes in the file Trial.py contained in ConstantContact folder. I am using the following code but it is not able to import the class.

import sys
sys.path.append('C:\\Users\\psinghal\\PycharmProjects\\ConstantContact\\constant-contact-python-wrapper')
import constant-contact-python-wrapper

API_KEY = "KEY" #not a valid key
mConnection = CTCTConnection(API_KEY, "joe", "password123")

Would someone please be able to point me to the right direction?

Patthebug
  • 4,647
  • 11
  • 50
  • 91

2 Answers2

1

constant-contact-python-wrapper and ConstantContact are unrelated packages for python. Create a __init__.py in the same directory as manage.py and it should work as expected.

pad
  • 2,296
  • 2
  • 16
  • 23
1

Part of the problem that you're trying to rectify is that you have two libraries that are together in the same scope, even though it doesn't look they necessarily need to be.

The simplest solution would be to simple put constant-contact-python-wrapper in the ConstantContact folder under a new folder for code you will be importing that you yourself did not write. This way your project is organized for this instance and for future instances where you import code that is from another library

Ideally the folder structure would be:

ConstantContact
|___ ConstantContact
    |____ExternalLibraries #(or some name similar if you plan on using different libraries)
         |___constant-contact-python-wrapper

Using the above model, you now have an organized hierarchy to accommodate imported code very easily.


To facilitate easy importing you would additionally setup the following:

1.Create init.py file in ExternalLibraries. The contents would be the following:

from constant-contact-python-wrapper import #The class or function you want to use

This will facilitate imports and can be extended for future libraries you choose to use.

You can then use import statements in your code written in the ConstantContact folder :

from ExternalLibraries import #The class or function you chose above

if you have multiple classes you would like to import, you can seperate them in your import statement with commas. For example:

from Example import foo,bar,baz

Since the init.py file in ExternalLibraries is import all functions/classes directly, you can use them now without even having to use dot syntax (ie. library.func).

Sources and further reading:

"all and import *" Can someone explain __all__ in Python?

"Python Project Skeleton" http://learnpythonthehardway.org/book/ex46.html

"Modules" http://docs.python-guide.org/en/latest/writing/structure/#modules

Community
  • 1
  • 1
Max Humphrey
  • 65
  • 1
  • 9