1

I am trying to import some variables from a different python file resides in the same directory from a another python file.

been trying this thing for hours and I still couldn't get the variables to use.

I have two files in the same directory as below:

const.py

test.py

This is how const.py looks like

FOO = 1234
NAMESPACE = "default"
DEPLOYMENT_NAME = "deployment-test"
DOCKER_IMAGE_NAME = "banukajananathjayarathna/bitesizetroubleshooter:v1"
SERVICE_CLUSTER = "deployment-test-clusterip"
SERVICE_NODEPORT = "deployment-test-nodeport"
INGRESS_NAME = "deployment-test-ingress"

and this is how my test.py looks like:

import os 
from . import constant

print(constant.FOO)

error I am getting:

ImportError: attempted relative import with no known parent package

Why is it so hard to do this with Python?

Jananath Banuka
  • 2,951
  • 8
  • 57
  • 105

2 Answers2

1

This is what test.py should look like:

from const import FOO

print(FOO)
Marcel Kämper
  • 304
  • 5
  • 16
1

If you want to get all variable statements as they are you should do:

from const import *

print(FOO)
print(NAMESPACE)

If you want to import variables under module name (file name), you should do:

import const

print(const.FOO)
print(const.NAMESPACE)

If you want to import variables under module name but want to access with constant:

import const as constant

print(constant.FOO)
print(constant.NAMESPACE)

The file name is the module name.

Guven Degirmenci
  • 684
  • 7
  • 16