user3696153
user3696153

Reputation: 752

python local module import problems

Usng Python 3.6

Hi, I have a python module with multiple PY files - I'd like to keep the name hierachy but cannot.

In effect, I can do this:

from .DOTNAME import * <-- works

I effectively want this:

import .DOTNAME as NAME <-- This does not.

I have for example

module:
    __init__.py <-> module init
    constants.py
        contains:  ONE =1 and TWO =2
    foo.py
        I want to refer to "constants.ONE" and "constants.ONE" but cannot
    bar.py
        I want to refer to "constants.ONE" and "constants.TWO" but cannot

What I want to do is in foo and bar.py, import the local module constants.py (PY file) as constants thus keeping the "constants" prefix

to do that, In the file foo.py, I do this:

import constants - but cannot, it says: NO SUCH MODULE - this only happens in modules not external to modules

I can do this: import .constants *, but then I cannot use constants.ONE or constants.TWO, I need to use the names ONE and TWO, I want to clearly identify these as constants.ONE and constants.TWO (same with other methods/functions in other modules)

How can I import a local module (py file) but keep the module name as the prefix I want to avoid using IMP() - I've seen a method elsewhere that suggests this and I don't think that is proper or pythonic way

Upvotes: 1

Views: 178

Answers (2)

fusion
fusion

Reputation: 1397

In your foo.py, you need to do:

import module.constants as constants

print(consants.ONE,constants.TWO)

Upvotes: 0

AmineBTG
AmineBTG

Reputation: 697

You can create a class inside constant.py and assign ONE and TWO as class attributes:

class Constant:
   ONE = 1
   TWO = 2

then import the Constant class from the constant.py module

from .constant import Constant
print(Constant.ONE)
print(Constant.TWO)

Upvotes: 1

Related Questions