Toothpick Anemone
Toothpick Anemone

Reputation: 4636

How do I import my own python files?

In a file named BinarySearch.py I have the following:

class SearchResult:    
    def __init__(self):
        self.was_found = False
        self.index = 0
    def __str__(self): 
        s = "SearchResult"
        s = s + "  was found:  "
        s = s + str(self.was_found) + "index:  " + str(self.index)
        return s

In another file, let's say it is named file2.py I have:

import os
cwd = os.getcwd()
import sys
sys.path.append(cwd)

import BinarySearch

However, when I try to run file2.py, I get the following error message:

NameError: name 'SearchResult' is not defined

It looks like the import BinarySearch did not actually import BinarySearch

I am using the Spyder IDE. Both files (BinarySearch.py and file2.py) are in the same directory. Also, I went to Tool > PYTHONPATH manager and added the directory to the path. I also tried restarting spyder to see if that was what was required for the path change to go into effect. It still doesn't work.

EDIT:

The line in file2.py which threw the error was the following:

sr = SearchResult()

Originally I assumed that the statement import BinarySearch would have the same behavior as if I copied the entire contents of BinarySearch.py and pasted it right where the import statement was inside file2.py. I see now that's not how import works.

Upvotes: 2

Views: 4763

Answers (2)

Toothpick Anemone
Toothpick Anemone

Reputation: 4636

One solution seems to be to change the import statement from

import BinarySearch

to:

from BinarySearch import *

The star/asterisk essentially means "import all," which imports everything from the file BinarySearch.py, including the SearchResult class.

The regular plain simple import also imports everything, but forces you to access things through a namespace. Everything from the file BinarySearch.py is now inside the namespace BinarySearch. We could leave the original import statement alone, but anytime we use something in file2.py which comes from BinarySearch we would have to add a prefix. We would have code that looks like this:

# inside file named file2.py
sr = BinarySearch.SearchResult()

If we get tired of writing BinarySearch. before things all the time, we can create an alias for the namespace, like so:

import BinarySearch as bs

Then, inside file2.py, the statement sr = bs.SearchResult() will work just fine.

Upvotes: 0

dacada
dacada

Reputation: 136

The current directory is already in the path without you having to explicitly put it there in any way (through the IDE or through sys.path)

In your second piece of code you're missing the last line which I asume is giving you the error, and most likely is something like

print(SearchResult())

It should be

print(BinarySearch.SearchResult())

Or you could change your import to

from BinarySearch import SearchResult

And then you can just do

print(SearchResult())

Upvotes: 5

Related Questions