简体   繁体   中英

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

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)

In your foo.py , you need to do:

import module.constants as constants

print(consants.ONE,constants.TWO)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM