1

I have a python file in the location 'lib/lib_add_participant.py'.And I declared a class in the file.

Now I want to call the class functions from the file call_participant.py.

I tried this code from lib/lib_add_participant.py import LibAddParticipant

Its not worked.Please correct me(I am coming from Ruby).

shajin
  • 3,214
  • 5
  • 38
  • 53

2 Answers2

4

If your file structure is as follows:

myproject/
    __init__.py
    call_participant.py
    lib/
        __init__.py
        lib_add_participant.py

In this case, your __init__.py files can be empty, if you like (or they can define any number of things - see this fine answer from Alex Martelli for more details.

then you can add it by using

from .lib.lib_add_participant import LibAddParticipant

However, if call_participant.py is your end script, then this tactic will not work, because you "can't do a relative import in a non-package", as the interpreter will tell you. In that case, your best bet (in my opinion, at least) is to make lib into a package in your python path (either in your site-packages directory, or in a path referred to by your pythonpath environment variable).

Community
  • 1
  • 1
Nate
  • 12,499
  • 5
  • 45
  • 60
0

Assuming lib is in a directory listed in your PYTHONPATH, try

from lib.lib_add_participant import LibAddParticipant
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • If lib is listed in $PYTHONPATH it would be: `lib_add_participant import LibAddParticipant`. If lib is in one of directories listed in $PYTHONPATH then your code will work, but only if there is an `__init__.py` file there too. – Jacek Konieczny Jul 20 '11 at 19:03