1

constants.py

import os
from datetime import date
dates       = datetime.datetime.now().strftime("mon_%m_day_%d_%H_%M")
out_dir = 'C:\\'+'_'+dates+os.sep

file_a.py

from constants import *
# Use out_dir

file_b.py

from constants import *
# Use out_dir

In the above code, I create a directory with the current date and time embedded in the name. Then I import that file in 2 separate .py files. However, I find that the out_dir changes in file_b.py as the date has changed. any ideas on how to fix this?

Alternatively, is there a way to find out when out_dir is changing?

user308827
  • 21,227
  • 87
  • 254
  • 417
  • Assuming that either constants.py or file_a.py write a file to the directory, file_b.py should attempt to find that directory by looping backwards in minutes. – 576i Apr 09 '15 at 14:49
  • You should provide a [MCVE](http://stackoverflow.com/help/mcve) --there is at least a typo in the `import` and the code you provide doesn't fail by itself. I assume that there is (you do) some update to `out_dir` and _then_ it fails. See my answer if that's the case. – MariusSiuram Apr 09 '15 at 15:40

2 Answers2

2

Because you are reassigning the variable, the reference of the first out_dir is different to the second out_dir. This means that, although it feels like the same (because the name is the same name) they are internally two different (disjoint) memory locations.

To address this behaviour simply change your imports to:

import constants

and use them like

constants.out_dir

This ensures that you make a lookup to the module constants, and thus you will have access to the last assignment.

MariusSiuram
  • 3,380
  • 1
  • 21
  • 40
1

When Python imports modules, all the code in module evaluated as is only once. So when you run your script, in all modules that imports constans.py, you must get the same value of out_dir.

You say you get different results.

  1. Are you run your scripts as different "sessions"?
  2. Do you use reload() function anywhere in your script?
  3. Add line print "imported constants"

And you have wrong imports.

import os
import datetime
`print "imported constants"`
dates = datetime.now().strftime("mon_%m_day_%d_%H_%M")
out_dir = 'C:\\'+'_'+dates+os.sep

If you see text imported constants more then once, this means you have troubles with reload()

Alexander R.
  • 1,756
  • 12
  • 19
  • @user308827 Take a look at [Why is Python running my module when I import it, and how do I stop it?](http://stackoverflow.com/questions/6523791/why-is-python-running-my-module-when-i-import-it-and-how-do-i-stop-it) – rosshamish Apr 09 '15 at 14:45
  • thanks, is there a way I can initialize dates only once? – user308827 Apr 09 '15 at 14:48
  • thanks, ultimately the problem was related to a combination of using multiprocessing and global variables together. This was not reflected in my question since I did not know that it would be an issue. – user308827 Apr 09 '15 at 22:19