6

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user2497792
  • 505
  • 2
  • 9
  • 18
  • Why do you need this? can you explain so that we can provide an optimal answer? – Aswin Murugesh Jun 27 '13 at 15:19
  • Perhaps the function does not belong in the class. It sounds like a helper function that does not refer to the object's state. – Steven Rumbalski Jun 27 '13 at 15:20
  • Yes sure, I have a function which converts numbers to a specific formatted string and did not wish to define the same exact function for each module. While I could do that it seems to me to be quite redundant and obviously not the most elegant solution – user2497792 Jun 27 '13 at 15:23
  • @user2497792: I think you misunderstand. I'm not suggesting that you re-implement the function for each module. I'm suggesting that you implement it once and import it as needed. There is nothing inelegant about using functions. – Steven Rumbalski Jun 27 '13 at 15:25
  • That is indeed the solution I am looking to accomplish, and I would hope not functions are a staple to quite a bit of programming, I am just new to python and still learning of it's features/syntax – user2497792 Jun 27 '13 at 15:37

1 Answers1

7

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

Community
  • 1
  • 1
ChrisProsser
  • 12,598
  • 6
  • 35
  • 44