0

I've split a program into three scripts. One of them, 'classes.py', is a module defining all the classes I need. Another one is a sort of setup module, call it 'setup.py', which instantiates a lot of objects from 'classes.py' (it's just a bunch of variable assignments with a few for loops, no functions or classes). It has a lot of strings and stuff I don't want to see when I'm working on the third script which is the program itself, i.e. the script that actually does something with all of the above.

The only way I got this to work was to add, in the 'setup.py' script:

from classes import *

This allows me to write quickly in the setup file without having the namespace added everywhere. And, in the main script:

import setup

This has the advantages of PyCharm giving me full code completion for classes and methods, which is nice.

What I'd like to achieve is having the main script import the classes, and then run the setup script to create the objects I need, with two simple commands. But I can't import the classes script into the main script because then the setup script can't do anything, having no class definitions. Should I import the classes into both scripts, or do something else entirely?

Cirrocumulus
  • 520
  • 3
  • 15

1 Answers1

0

Import in each file. Consider this SO post. From the answer by Mr Fooz there,

Each module has its own namespace. So for boo.py to see something from an external module, boo.py must import it itself.

It is possible to write a language where namespaces are stacked the way you expect them to: this is called dynamic scoping. Some languages like the original lisp, early versions of perl, postscript, etc. do use (or support) dynamic scoping.

Most languages use lexical scoping instead. It turns out this is a much nicer way for languages to work: this way a module can reason about how it will work based on its own code without having to worry about how it was called.

See this article for additional details: http://en.wikipedia.org/wiki/Scope_%28programming%29

Intuitively this feels nicer too, as you can immediately (in the file itself) see which dependencies the code has - this will allow you to understand your code much better, a month, or even a year from now.

Community
  • 1
  • 1
Nelewout
  • 6,281
  • 3
  • 29
  • 39
  • Thank you for your answer and for the SO post. It seems logical now: a year from now I read script C, see that it imports B, then I read B and see that it imports A. I just wasn't sure this was a good habit to acquire :) Thanks a lot. – Cirrocumulus Sep 18 '16 at 19:08