0

I like to organize my data analysis projects with a root folder containing a data folder (named data) and a code folder (when I use R, I sometimes name it R). When using Python, my code folder would logically be called python. My project working directory is the root folder (containing both data and python folders).

I have multiple files of code in my python folder. I would like to import one (let's call it file2.py) from another, in an interactive python session. I have tried the following:

from .python import file2

However, this does not work because python is a reserved word. If I rename the folder to something different, it works. Is there a way to escape the reserved word, or pass the file location as a string to the import? I'm frustrated because all the best alternatives (e.g., code, scripts) are also reserved words. My project organization is an oft-recommended best practice in R, and I'm hoping there's a parallel in Python.

dyoung
  • 87
  • 6
  • 6
    `python` is not a [reserved word](https://stackoverflow.com/questions/22864221/is-the-list-of-python-reserved-words-and-builtins-available-in-a-library) – pault Oct 22 '19 at 01:24
  • 1
    if you are in the folder in which the python folder resides, do from python import file2...make sure it includes a `__init__.py` – Derek Eden Oct 22 '19 at 01:25
  • 2
    I can't reproduce the problem as stated. None of the words you mention are reserved. Is `from .python import file2` actually being run from within a package? From your description, that's not the case; relative imports are only valid from an actual package; that is, there must be a directory *under* the working directory (or *under* another entry in `sys.path`) that has your code in it, and also has a subdirectory named `python`, containing `file2.py`. From your description, `python` is directly under your working directory, so your code should be doing `from python import file2` (no `.`). – ShadowRanger Oct 22 '19 at 01:31
  • 1
    @DerekEden: In Python 3, the `__init__.py` isn't necessary, thanks to [PEP 420: Implicit Namespace Packages](https://www.python.org/dev/peps/pep-0420/). – ShadowRanger Oct 22 '19 at 01:32
  • Thank you @DerekEden and @ShadowRanger. `from python import file2` works. I swear I tried that before without success, but it is working now! – dyoung Oct 22 '19 at 01:39
  • 1
    no problem...sometimes from experience you just need someone to hover over your shoulder and watch you do things you've already done and they seem to work XD – Derek Eden Oct 22 '19 at 13:20

1 Answers1

1

Your code is not running as a package. Therefore, you need to run from python import file2, not from .python import file2.

pppery
  • 3,731
  • 22
  • 33
  • 46