-4

Python newbie here. Let's say I have two Python scripts main.py and lib.py. There is a variable (not a function) in lib.py that I want to use in main.py. I imported lib.py in main.py and called lib.variable. I still receive the classical import error ('module' has no attribute called 'variable') and I don't get why. Both files remain in the same directory and I triple ckecked for typo. I also tried the 'from lib import variable' command, with no results.

What am I doing wrong?

Crolle
  • 822
  • 3
  • 10
  • 20
  • 1
    Print your code, it will be much faster. – Kobi K Dec 09 '13 at 12:58
  • 2
    Alright folks, I fixed this. Both files were calling on each other! main.py was importing lib.py (where variable was called) before variable was defined in main.py Take home message : always import stuff properly. – Crolle Dec 09 '13 at 13:24
  • Take home message: post your code! You would probably have realised the issue when constructing the question. – cdarke Dec 10 '13 at 08:55

2 Answers2

1

Works for me. Here's how:

lib.py:

variable = 42

main.py:

import lib

print lib.variable

Another version of main.py:

from lib import variable

print variable

You don't show your code, so any other hints would be a guess. One guess might be that you have another module called lib.py that is being loaded instead.

Note that import names are case-sensitive, even on Windows.

cdarke
  • 42,728
  • 8
  • 80
  • 84
  • PEP-8 says "modules all lowercase": http://www.python.org/dev/peps/pep-0008/#package-and-module-names – xbello Dec 09 '13 at 16:19
  • @xbello: Doh! post changed. – cdarke Dec 10 '13 at 08:53
  • Got this error: No module named '__main__. I just have a collection of python files and want to import a variable from one file into other. – saran3h Jun 25 '18 at 14:06
  • @saran3h: create a new question, post a minimal amount of code to reproduce the problem, and the full error trace. It sounds like your `import` is wrong, but that's a guess. – cdarke Jun 25 '18 at 22:25
0

This is a blind bet (post some code!), but if you imported lib.py, try importing just lib (without .py).

xbello
  • 7,223
  • 3
  • 28
  • 41