What is the point of importing at the beginning of a file?

In Week 3 Assignment 2, Exercise 1 we have code for the conv_block like:
conv = Conv2D(n_filters, …

I was wondering how a call like this would work, without prepending tfl.Conv2D etc. Then I looked at the beginning of the file and see

from tensorflow.keras.layers import Conv2D

So I am assuming that this creates a shorthand where we can write “Conv2D” anytime we would have written “tensorflow.keras.layers.Conv2D”.

Is this simply syntactic sugar, or is there any benefit to importing at the beginning of a project?

Python code in one module gains access to the code in another module by the process of importing it.

The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope.

1 Like

Thank you. Does the code run quicker by importing everything you need at the beginning rather than each line as needed then?

Not that I know of, though I never instrumented to test. Python allows you to put import statements wherever, but IMO it’s nice to see all the dependencies in one place. Never fun to get part way through executing only to have it fail on unrecognized name or module not found buried deep in the code. I generally put them all in the first executable cell in a notebook. It’s like glancing at the cast of characters before the opera starts.

1 Like