0

I'm new here and in python.

I try to import only a single variable or some of them from another file. I try from conf import SINGLE_VARIABLE but it gives me a ImportError: cannot import name 'SINGLE_VARIABLE

Maybe it is not a good idea in the python way of coding, but I'm curious if it is possible

Thx

freezed
  • 1,269
  • 1
  • 17
  • 34
  • 2
    Yes it is possible. The error message says it cannot find `SINGLE_VARIABLE` in `conf` – Sohaib Farooqi Feb 10 '18 at 07:35
  • 3
    `from conf import SINGLE_VARIABLE` is a good coding style and it will work as long as something named `SINGLE_VARIABLE` is actually in `conf`. – John1024 Feb 10 '18 at 07:35
  • You can study the module content with `print(dir(module))` or `print(help(module))` . – Mr. T Feb 10 '18 at 07:46
  • 1
    Make sure SINGLE_VARIABLE is declared outside a function. – cdarke Feb 10 '18 at 07:52
  • 1
    can you provide your code ? – K P Feb 10 '18 at 08:04
  • see if this answer help you [https://stackoverflow.com/questions/19993795/how-would-i-access-variables-from-one-class-to-another](https://stackoverflow.com/questions/19993795/how-would-i-access-variables-from-one-class-to-another) – K P Feb 12 '18 at 05:52
  • Thx for suggesting @KushalParikh but it's not the same case. – freezed Feb 12 '18 at 20:52

2 Answers2

3

just make sure your varialbe is global for use

hello1.py

fname = "hello"
lname = "world"

hello2.py

from hello1 import fname
print(fname)

output

hello

works with python 3.x

K P
  • 854
  • 7
  • 19
0

OK, thanks for answering people.

I just ommit to say that I want to import my variable from a Class… and in this case, import must be inside the appropriate method.

For memory, see my (working) code:

file1.py:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from file2 import Message

WORD_LIST = ["hello","bonjour","ola"]

Message(1)

file2.py:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class Message:

    def __init__(self, index):
        from file1 import WORD_LIST
        self._phrase = WORD_LIST[index] + " world"

    def __str__(self):
        return self._phrase
freezed
  • 1,269
  • 1
  • 17
  • 34