Do imported files always have to be in the same directory?


In the context of this exercise, do imported files always have to be in the same directory as the file we are importing to?


No, files can be imported from different directories.

There are a few ways you can do this, and one of them is importing a file from a subdirectory. For example, say that you have this folder structure,

--> functions

In the file, we can import a function from the file, like so

from functions.file import function1

One thing to note when importing a file from another directory in this way, is that you would need to include a file named in the same directory of that file being imported. In the above example folder structure, we included in the same directory as This lets Python know that a file is a package from which to import modules from.


how can we import more than one function form the same file?


how to import all these functions together in another file


import library   # note that we omit the  .py suffix

x = library.function1()      # called using "dot notation"
y = library.function2()
# etc

If you don’t want to type “library” each time:

import library as lib   # note that we omit the  .py suffix

x = lib.function1()      # called using "dot notation"
y = lib.function2()
# etc

What would be the correct way to import a file from a different directory, but not in a subfolder of the current file?
My boss is new to python and wants all the custom code in a different directory branch from the one that new scripts are developed and ‘launched’ from, for example (borrowing from your example):

–> project
–> functions
----> __ init

this is how the business code development is done using php so just ‘not doing it that way’ is not an option I have.

what do I do?


This appears to be very clear and complete.


you can do from library import* but use this * very carefully else not only it will pollute your namespaces but may conflict with local objects, functions.

I didn’t really understand how this works. Can you please brief about this.

Thank you for the link it really helps!!!

from library import *

The library here is a placeholder for any library or module you would want to import from (I think some used in the course include math and datetime). The * here indicates that you are importing all the variables and functions in that library or module.

However, note that using the * wildcard is not recommended.


Here, I’m sorry, but this works as well and isn’t it so much simpler?


# Import library below:
from library import always_three, always_four

# Call your function below:
print(always_three()) #Prints 3
print(always_four()) #Prints 4


def always_three():
  return 3

def always_four():
  return 4

You just need to use a comma between multiple functions you want to import…
no need to define new variables and clutter your code with extra lines! :wink: