0

I'm working on my first project and am trying to figure out how something works. If I have a module that store some functions I will reference in my main program that depend on another module, where do I include the import statement?

For example:

# Title: func.py

import os

def my_function(path):
    if not os.path.isfile(path):
        parser.error(f'The file {path} does not exist.')

Do I include import os here, or can I simply have it in the main document?

DH995
  • 13
  • 2
  • You must `import` the module in the file that references the module. So if you have a file that somewhere calls `os.path.isfile`, you need to `import os` at the top of that file. – larsks Jan 08 '22 at 22:43
  • `import` statements do two things: 1) create a module if necessary, and 2) bind the module to a name in the current scope. Python doesn't have a process-wide global scope (other than the built-in scope, which is effectively read-only), only per-module global scopes. – chepner Jan 08 '22 at 22:44
  • Got it. In this case, I will be calling the whole module so it doesn't matter. But is there a better way to write this so I wouldn't get an error if I ran something like `from funcs import my_function` since `os` would never have been imported? – DH995 Jan 08 '22 at 22:50
  • Each function has a reference to its global namespace. You don't need the names that `my_function` uses in the *calling* namespace for `my_function` to work. – chepner Jan 08 '22 at 22:52
  • the [PEP 8 - Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) says to always [put them at the top of the file](https://www.python.org/dev/peps/pep-0008/#imports). – martineau Jan 09 '22 at 00:47

1 Answers1

0

You must import the module in the file that references the module. So if you have a file that somewhere calls os.path.isfile, you need to import os at the top of that file.

-- comment by larsks

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    Note that generally when trying to use `x.y.z` it is not sufficient to `import x`. `os.path` is a special case, see https://stackoverflow.com/questions/2724348/should-i-use-import-os-path-or-import-os – mkrieger1 Jan 08 '22 at 23:00
  • 1
    Yeah, it's unfortunate that dotted module names look exactly like attribute access. – chepner Jan 08 '22 at 23:02