Import Python Script Into Another?


I'm going through Zed Shaw's Learn Python The Hard Way and I'm on lesson 26. In this lesson we have to fix some code, and the code calls functions from another script. He says that we don't have to import them to pass the test, but I'm curious as to how we would do so.

Link to the lesson | Link to the code to correct

And here are the particular lines of code that call on a previous script:

words = ex25.break_words(sentence)
sorted_words = ex25.sort_words(words)

sorted_words = ex25.sort_sentence(sentence)
print sorted_words
6/6/2015 5:09:30 PM

Accepted Answer

It depends on how the code in the first file is structured.

If it's just a bunch of functions, like:


def foo(): print("foo")
def bar(): print("bar")

Then you could import it and use the functions as follows:

import first    # prints "foo"    # prints "bar"


from first import foo, bar

foo()          # prints "foo"
bar()          # prints "bar"

or, to import all the symbols defined in

from first import *

foo()          # prints "foo"
bar()          # prints "bar"

Note: This assumes the two files are in the same directory.

It gets a bit more complicated when you want to import symbols (functions, classes, etc) in other directories or inside modules.

7/30/2016 11:19:53 PM

It's worth mentioning that (at least in python 3), in order for this to work, you must have a file named in the same directory.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow