4

I tried the answers in this question to no avail so I thought it'd be worth a separate question. The directory layout is as follows:

aale/
     2/
       2.py
       __init__.py
     3/
       3.py
       __init__.py
     __init__.py

The names are unfortunately unable to change (this is the layout given to us for a HW problem). I am trying to import 2 from 3 but it doesn't seem to be working. I tried using importlib as:

two = importlib.import_module('2.2') as well as two = importlib.import_module('2')

which didn't work also (gave a ModuleNotFoundError: No module named '2' error). Any help / other methods would be appreciated. I am using Python 3.6.

AJwr
  • 506
  • 1
  • 4
  • 22

3 Answers3

3

Assuming your script is in the aale directory, you will need to do your import like:

two = importlib.import_module('aale.2.2')
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
2

You can use __import__, i.e.:

two  = __import__("2.2") # or __import__("aale.2.2") 
three = __import__("3.3") # or __import__("aale.3.3")

Equivalent to:

import 2.2 as two  
import 3.3 as three

which isn't possible.


Notes:

  1. According to PEP 8 styling guide:

    Package and Module Names should have short, all-lowercase names. Underscores can be used in the module name if it improves readability.

  2. I've tested the imports using the same folder structure as in your question and no errors were shown.

References:

  1. https://stackoverflow.com/a/16644280/797495
  2. In python, how to import filename starts with a number
  3. PEP 8 -- Style Guide for Python Code
Community
  • 1
  • 1
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
0

You can use pathlib

It is basic:

from pathlib import Path


BASE_LOCATION = Path(__file__).parent

(You can add .parent to get to the folder above and so on.)

Edit

If this doesn't help you, you can try import weirdimport.

You can read more about this here.

Hope this helps!

Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
  • Sorry, I'm unsure as to how to use this. Should I be using `importlib` on the path I get from this? – AJwr Sep 16 '18 at 15:47
  • In @Stephen's answer, you said you get `ModuleNotFoundError: No module named 'aale'` so in addition to his solution you can add the path from pathlib – Moshe Slavin Sep 16 '18 at 15:49