Ayaz
Ayaz

Reputation: 376

Import twisted modules in functions Instead of at the beginning

I am reading great python twisted tutorial http://krondo.com/?page_id=1327 little bit confusion, in many examples there is importing twisted reactor or other module multiple time in a python file instead of at the beginning. Because in python way we use import modules at the file beginning. Any one can elaborate it.

Upvotes: 0

Views: 91

Answers (1)

Iguananaut
Iguananaut

Reputation: 23346

In general you're correct--in Python as in most languages the relevant import statements in a module should be at the beginning of the module where they're easily found. In most cases that's desirable so that's how it's taught.

But like most rules there are exceptions. Python allows import statements within function and class definitions as well as at the module level. One good reason to put an import inside a function is that some imports can actually be fairly expensive, time-consuming operations.

In the case of Twisted's from twisted.internet import reactor there's a lot of extra work and magic going on behind the scenes. So it makes more sense to defer that import until it's actually needed--preferably within a function that will only be called once (or on rare occasions). Another reason specific to Twisted (the aforementioned "magic") is that the very act of importing reactor creates a singleton instance of that object, and other code can affect how the reactor instance is created. So we defer importing the reactor until any other setup code has had a chance to execute.

One final reason that it's sometimes necessary to use these kinds of in-line imports is the problem of circular imports. I won't go into detail about that here unless you ask, but I think you can find some other discussions of that problem on this site.

Upvotes: 1

Related Questions