3-1-5-20. Importing Local Scripts

organize your code into multiple files and reuse code in those files.

If the Python script you want to import is in the same directory as your current script,

you just type import,

followed by the name of the file without the dot PY extension.

Imports statements are written at the top of a Python script,

each one on a separate line.

Python will still run if imports statements are included later in the script,

but it’s common practice to always have these at the top.

You’re only able to access what you’ve imported after this statement so,

it’s just less confusing to have these written first.

It’s also nice for readers to see what a script

depends on before reading the rest of the code.

Let’s start with a really simple example.

Here, I have a Python file called other_script.py that just prints two plus three.

In this file demo.py,

I import other_script and then print four.

When we run demo.py,

this import statement tells Python to run code from that file which prints five.

It then continues to execute the rest of the code in this file printing four.

If instead this file had the line num equals two plus three,

and we try to access this in demo.py,

referencing it with just the name of the variable would return an error.

To access objects in other_script.py,

we need to use the name of the file followed by a dot,

followed by the object to tell Python to look

for this object in the other_script file we imported.

Now, it accesses the variables successfully.

When Python runs the script.

It only has direct access to objects defined in the script.

One of these objects is a module called other_script.

A module is just a file with Python definitions and statements.

When we import a Python file like this,

it creates an object called other_script with a type module.

Let’s see a more useful example of importing a module.

Here, we have a Python file that contains useful functions we would like to use.

One, that returns the mean of a list and one that adds five to each element of a list.

We can import them into demo.py,

and type useful_functions dot the name of the function to use them.

You can imagine this would be very helpful if

we had many functions used a lot in different files.

Although, it seems a little annoying that we have to type out

the whole name of the file each time we want to use a function from it.

We can make this much simpler by adding an alias.

Here, I made an alias for the useful_function module UF.

Now, I can just type UF instead of the whole module name when calling functions from it.

This is useful when we have objects we want

to import from other Python scripts like functions.

But, what if that script also includes

executable statements in addition to function definitions that we don’t want to import.

For example, what if useful_functions.py has code

at the bottom of the script that tests its functions and prints the results?

This code is nice if we run useful_functions.py to test out these functions,

but unnecessary if we’re just trying to use these functions in another script.

Here is where we can use this statement if name equals main.

By including these executable statements inside this if main block,

we tell Python to execute this code only when

the main program being executed is this useful_functions.py.

If we run this file the code inside this block is run.

However, if we run another script that simply imports

useful_function.py this code is not run.

Generally, it’s good practice to write executable statements inside

an if name block or alternatively include them

in a function called Main and call this in the if name block.

You’re probably wondering what this Name and Main stuff is.

Whenever we run a script like this,

Python actually sets a special built in variable called

Name with two underscores before and after it for any module.

Here, since we ran Python demo.py,

Python recognizes this module as the main program

and sets the name variable for this module to the string Main.

For any modules that are imported in the script,

this built-in name variable is just set to the name of that module.

파일에서 데이터를 읽는 것 외에도

실제로 다른 스크립트에서 Python 코드를 가져올 수 있습니다.

이것은 더 큰 프로젝트에서 작업할 때 특히 유용합니다.

코드를 여러 파일로 구성하고 해당 파일에서 코드를 재사용합니다.

가져오려는 Python 스크립트가 현재 스크립트와 동일한 디렉토리에 있는 경우,

import를 입력하면 됩니다.

뒤에 점 PY 확장자가 없는 파일 이름이 옵니다.

Imports 문은 Python 스크립트 상단에 작성되며,

각각 별도의 줄에 있습니다.

import 문을 나중에 스크립트에 포함하면 Python은 계속 실행됩니다.

그러나 이것들을 항상 맨 위에 두는 것이 일반적입니다.

이 명령문 이후에 가져온 항목에만 액세스할 수 있으므로,

이것들을 먼저 쓰는 것이 덜 혼란스러울 뿐입니다.

독자가 대본을 보는 것도 좋습니다.

나머지 코드를 읽기 전에 에 따라 다릅니다.

정말 간단한 예부터 시작하겠습니다.

여기에 2 더하기 3을 인쇄하는 other_script.py라는 Python 파일이 있습니다.

이 파일 demo.py에서

other_script를 가져온 다음 4개를 인쇄합니다.

우리가 demo.py를 실행할 때,

이 import 문은 5를 출력하는 해당 파일에서 코드를 실행하도록 Python에 지시합니다.

그런 다음 4를 인쇄하는 이 파일의 나머지 코드를 계속 실행합니다.

대신 이 파일에 줄 번호가 2 더하기 3인 경우,

우리는 demo.py에서 이것을 액세스하려고 합니다.

변수 이름만으로 참조하면 오류가 반환됩니다.

other_script.py의 객체에 액세스하려면,

파일 이름 다음에 점이 와야 합니다.

다음에 파이썬에게 보도록 지시하는 객체가 옵니다.

가져온 other_script 파일의 이 개체에 대해

이제 변수에 성공적으로 액세스합니다.

Python이 스크립트를 실행할 때.

스크립트에 정의된 개체에만 직접 액세스할 수 있습니다.

이러한 개체 중 하나는 other_script라는 모듈입니다.

모듈은 파이썬 정의와 명령문이 있는 파일일 뿐입니다.

이와 같이 Python 파일을 가져올 때,

유형 모듈을 사용하여 other_script라는 개체를 만듭니다.

모듈을 가져오는 더 유용한 예를 살펴보겠습니다.

여기에 우리가 사용하고 싶은 유용한 기능이 포함된 Python 파일이 있습니다.

하나는 목록의 평균을 반환하고 다른 하나는 목록의 각 요소에 5를 더합니다.

우리는 그것들을 demo.py로 가져올 수 있습니다.

그리고 사용할 함수의 이름에 유용한 기능을 입력합니다.

다음과 같은 경우에 이것이 매우 도움이 될 것이라고 상상할 수 있습니다.

우리는 다른 파일에서 많은 기능을 많이 사용했습니다.

하지만, 우리가 입력해야 하는 것이 약간 성가신 것처럼 보이지만

함수를 사용하려고 할 때마다 파일의 전체 이름.

별칭을 추가하여 훨씬 간단하게 만들 수 있습니다.

여기에서는 utility_function 모듈 UF의 별칭을 만들었습니다.

이제 UF에서 함수를 호출할 때 전체 모듈 이름 대신 UF를 입력할 수 있습니다.

이것은 우리가 원하는 객체가 있을 때 유용합니다.

함수와 같은 다른 Python 스크립트에서 가져올 수 있습니다.

그러나 해당 스크립트에

가져오고 싶지 않은 함수 정의 외에 실행 가능한 문.

예를 들어, 유용한_기능.py에 코드가 있으면 어떻게 될까요?

기능을 테스트하고 결과를 인쇄하는 스크립트의 맨 아래에?

이 코드는 이 함수를 테스트하기 위해 유용한_functions.py를 실행하면 좋습니다.

그러나 다른 스크립트에서 이러한 기능을 사용하려는 경우에는 불필요합니다.

여기에서 name이 main과 같으면 이 명령문을 사용할 수 있습니다.

이 if 메인 블록 안에 이러한 실행 가능한 문장을 포함함으로써,

다음 경우에만 이 코드를 실행하도록 Python에 지시합니다.

실행 중인 주요 프로그램은 이 utility_functions.py입니다.

이 파일을 실행하면 이 블록 안의 코드가 실행됩니다.

그러나 단순히 가져 오는 다른 스크립트를 실행하면

utility_function.py 이 코드는 실행되지 않습니다.

일반적으로 내부에 실행 가능한 문을 작성하는 것이 좋습니다.

if 이름 블록 또는 대안으로 포함

Main이라는 함수에서 이 함수를 if 이름 블록에서 호출합니다.

이 Name과 Main 항목이 무엇인지 궁금할 것입니다.

이런 스크립트를 실행할 때마다

Python은 실제로 라는 특수 내장 변수를 설정합니다.

모든 모듈에 대해 앞뒤에 두 개의 밑줄이 있는 이름입니다.

여기서는 Python demo.py를 실행했기 때문에

파이썬은 이 모듈을 메인 프로그램으로 인식합니다.

이 모듈의 이름 변수를 Main 문자열로 설정합니다.

스크립트에서 가져온 모든 모듈의 경우

이 내장 이름 변수는 해당 모듈의 이름으로 설정됩니다.

Importing Local Scripts

We can actually import Python code from other scripts, which is helpful if you are working on a bigger project where you want to organize your code into multiple files and reuse code in those files. If the Python script you want to import is in the same directory as your current script, you just type import followed by the name of the file, without the .py extension.

import useful_functions

It’s the standard convention for import statements to be written at the top of a Python script, each one on a separate line. This import statement creates a module object called useful_functions. Modules are just Python files that contain definitions and statements. To access objects from an imported module, you need to use dot notation.

import useful_functions
useful_functions.add_five([1, 2, 3, 4])

We can add an alias to an imported module to reference it with a different name.

import useful_functions as uf
uf.add_five([1, 2, 3, 4])

Using a main block

To avoid running executable statements in a script when it’s imported as a module in another script, include these lines in an if __name__ == "__main__" block. Or alternatively, include them in a function called main() and call this in the if main block.

Whenever we run a script like this, Python actually sets a special built-in variable called __name__ for any module. When we run a script, Python recognizes this module as the main program, and sets the __name__ variable for this module to the string "__main__". For any modules that are imported in this script, this built-in __name__ variable is just set to the name of that module. Therefore, the condition if __name__ == "__main__"is just checking whether this module is the main program.

Try It Out!

Here’s the code I used in the video above. Create these scripts in the same directory and run them in your terminal! Experiment with the if main block and accessing objects from the imported module!

# demo.py

import useful_functions as uf

scores = [88, 92, 79, 93, 85]

mean = uf.mean(scores)
curved = uf.add_five(scores)

mean_c = uf.mean(curved)

print("Scores:", scores)
print("Original Mean:", mean, " New Mean:", mean_c)

print(__name__)
print(uf.__name__)
# useful_functions.py

def mean(num_list):
    return sum(num_list) / len(num_list)

def add_five(num_list):
    return [n + 5 for n in num_list]

def main():
    print("Testing mean function")
    n_list = [34, 44, 23, 46, 12, 24]
    correct_mean = 30.5
    assert(mean(n_list) == correct_mean)

    print("Testing add_five function")
    correct_list = [39, 49, 28, 51, 17, 29]
    assert(add_five(n_list) == correct_list)

    print("All tests passed!")

if __name__ == '__main__':
    main()

다음

%d