3

So for example: here I have fake.py file and real.py file. And in fake.py:

a = 'fake a'
b = 'fake b'

and in real.py:

from fake import*
a = 'real a'
print(a,b)

then it prints out: real a fake b

Why is that?
What if I want to use a in fake.py?
Do I have to use import fake and fake.a?

'statements within a module(fake in this example?) are executed only the first time a module is imported'

what does this mean ?

I am new to programming please help thank you.

Dayson D
  • 321
  • 2
  • 7

2 Answers2

4

Keep away from from some_module import * because you import all names from that module into your current module namespace.

This will - in case of a "name clash" - not only overwrite any previously defined names but they are also, as you've seen, likely to be overwritten.


Why is that?

The from fake import * in your case is very roughly equivalent to:

# equivalent to "from fake import *"
import fake
a = fake.a
b = fake.b
del fake

# Rest of the file
a = "real a"
print(a, b)

So no wonder that the "fake a" isn't accessible (nor printed).


Do I have to use import fake and fake.a?

That's a good start if you want to "reduce" the likelyhood of such name collisions:

import fake
a = "real a"
print(a, fake.a, fake.b)

But you could also use an alias:

import fake as f
a = "real a"
print(a, f.a, f.b)

You could also import specific names from fake (also with aliases):

from fake import a as fake_a, b as fake_b
a = "real a"
print(a, fake_a, fake_b)

As for

What if I want to use a in fake.py?

There should be no problem because there is no import in fake.py so no name collision there.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
1

Problem

You are importing two global variables from fake.py (a & b) and then assigning a new value to one of them (a).

Solution

If you would like to use fake.a and fake.b then get rid of the * in the import directive. Use this import directive:

import fake

Then you will be able to access the a & b variable with this form

fake.a
fake.b
trejas
  • 991
  • 7
  • 17