Try this simple test, create a file a.py with this content:
print "Importing a.py"
Then create b.py with this other content:
import a
Then create c.py with this other content:
def x():
import a
pass
Open a python interpreter and do:
>>> import b
It should print "Importing a.py", do the import again, it shouldn't print
anything. Now close the interpreter and start a new one and do:
>>> import c
>>> c.x()
>>> c.x()
It should print "Importing a.py" only once too.
Anyway, I would suggest you to follow PEP8 guideline http://www.python.org/dev/peps/pep-0008/
and leave function level import for cases where recursive imports is an issue.
Good luck,
Matías
Excerpts from Cal Leeming [Simplicity Media Ltd]'s message of Thu Jun 02 11:39:14 -0300 2011:
> Hey guys,
>
> This is more of a python question, than a Django specific one, but it's been
> bugging me for years now lol.
>
> I'm trying to figure out if it is better to do imports at the top of the
> file, or within the function/methods themselves.
>
> I guess the questions I'm asking are:
>
> - Is there any (serious) performance issues by doing imports every time
> the function/method is called
> - Is there a preferred style / guideline when it comes to imports? (maybe
> a PEP somewhere?)
> - Are relative imports discouraged? (from .. import package)
>
> Obviously, the answers would depend on different scenarios, so I'm looking
> for a discussion really, rather than a set in stone answer.
>
> Example 1:
> import os
> def test():
> print os.uname()
> def test2():
> print os.uname()
> test()
> test2()
>
> Example 2:
> import os
> class test:
> def test(self):
> print os.uname()
>
>
> Example 2:
> class test:
> def test(self):
> import os
> print os.uname()
> def test2(self):
> import os
> print os.uname()
>
> t = test()
> t.test()
> t.test2()
>
--
Matías Aguirre <matiasaguirre@gmail.com>
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
No comments:
Post a Comment