Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a single function to my main.py in Python from another module? [duplicate]

Tags:

python

import

In my script I have a function inside a module which I wish to be able to use in my main module to prevent redundancy. This other module (not my main, let's call it two.py) contains several classes and to import a class for use in another module one would use

from someDirectory.two import ClassA

Which works fine for importing the entire class, but say I have a function myFunction() in a different class ClassB contained in the same two.py module, which I want to be able to use in my main.py.

Is there a way which I can "grab" that function for use in my main.py or other modules, without having to import the entire class or redefine the same function?

like image 421
user2497792 Avatar asked Jun 27 '13 15:06

user2497792


1 Answers

You need to make sure that the directory you wish to import code from is in your system path e.g.:

sys.path.insert(0, path_to_your_module_dir)

Then you can go ahead and do

from module import function

UPDATE

The following thread has details of how to permanently add the directory to your pythonpath in either Windows or Unix-like systems:

Permanently add a directory to PYTHONPATH

like image 97
ChrisProsser Avatar answered Oct 01 '22 14:10

ChrisProsser