How to import functions of other file?

This is the place for queries that don't fit in any of the other categories.

How to import functions of other file?

Postby soria1201 » Tue Mar 19, 2013 8:33 pm

Hello,

i'm a beginner in programing and in Python. I'm following the book "Think Python http://www.greenteapress.com/thinkpython/thinkpython.pdf and doing the examples and exercises. I'm using Python 2.7 and working with the IDLE that comes with Python. Everything is Ok but i've a problem. I've a script with a few functions in it. Now, I'm writting another script (something like this http://thinkpython.com/code/flower.py) that need to use some functions from the first script (this one: http://thinkpython.com/code/polygon.py). Instead of rewritting again those functions, the solution in the example is to use the comand "from polygon import *". I've used that comand to import math and a package, but i dont know how to import a file.py into other file.
soria1201
 
Posts: 1
Joined: Sun Mar 17, 2013 12:11 am

Re: How to import functions of other file?

Postby setrofim » Tue Mar 19, 2013 8:45 pm

You can import .py files the same way you import standard modules/packages. The trick is in placing the .py file somewhere Pythong can find it. The simplest way is to place the module in the same directory as the script you want to import the module from. So if you have both flower.py and polygon.py in the same directory, then you should be able to say "from polygon import *" inside flower.py.

You can specify other locations where the modules are as well. Two common ways to do this are either to modify sys.path variable inside your script (which you can access by importing sys module), or by modifying the PYTHONPATH enviroment variable on your computer. You can read more about it here.
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests

cron