shajin
shajin

Reputation: 3264

How to include class from another file(in another folder) - python

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).

Upvotes: 1

Views: 5363

Answers (2)

Nate
Nate

Reputation: 12819

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).

Upvotes: 5

unutbu
unutbu

Reputation: 879361

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

from lib.lib_add_participant import LibAddParticipant

Upvotes: 0

Related Questions