97amarnathk 97amarnathk - 3 years ago 179
Python Question

What is include() in python? How is it different from import?

I am new to python and Django. I recently started with Django and in one of the tutorials I came across the following piece of code :

urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]


What does that include statement do? How exactly is it different from an
import
statement?


I know
import
statements are used to import some modules in python. And I read the following in the Django documentation already -


A function that takes a full Python import path to another URLconf module that should be “included” in this place. Optionally, the application namespace and instance namespace where the entries will be included into can also be specified


I am not able to understand the above line. I did try reading the documentation and also made a lot of google searches, but nothing else came up.

Answer Source

Just a quick and dirty answer.

Import is very vital statement for python, whereas include is limited to django and it vital for django. Import is used to import python modules whereas include is used in django to give it Modularity for apps.

Include() :

A function that takes a full Python import path to another URLconf module that should be “included” in this place. Optionally, the application namespace and instance namespace where the entries will be included into can also be specified

Import:

To use any package in your code, you must first make it accessible. You have to import it. You can't use anything in Python before it is defined. Some things are built in, for example the basic types (like int, float, etc) can be used whenever you want. But most things you will want to do will need a little more than that.

Update:

URLconf is a file (usually called urls.py) that has all the url pattern mapping for given particular app. In your example Polls is a app that has a URLconf file saved as urls.py( that is placed in polls folder). Now to dispatch request to your app urls (say http://example.com/polls/stats) dango need to include your urlconf which it does by Include statement. You could write all the content of polls.urls inside the main urls.py and complete remove the url(r'^polls/', include('polls.urls')),
Its not recommended because it looks ugly, increases repetition of code and removing app later on becomes a mess.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download