I&C SCI 32 Chapter Notes - Chapter 2: Local Variable, Global Variable, Eval

74 views5 pages
ICS 32 Fall 2015
Notes and Examples: Modules
Python programs that span multiple files
At a fundamental level, Python programs are written in much the same way as programs in almost every other programming
language in popular use: We write our code as text and store that text in files. To differentiate these files easily from others, we use
the extension .py on their filenames — and, as we'll see, this turns out to be a requirement, not just a good habit to get into — but
there is otherwise nothing special about them; they're just text files. (In fact, you can write Python programs that read Python
programs using the same techniques you've learned for reading from text files; you can even execute them using built-in functions
like eval() and exec() to run them in whole or in part.)
You can learn a lot about Python while writing only programs that are entirely stored in a single .py file, and there's a pretty good
chance that this is all you've done in your prior coursework. However, as programs grow beyond a certain size, it becomes important
to split them up into separate files of a practical size, rather than writing them as one giant file. You can imagine, for example, that a
400,000-line program written by many people over a period of multiple years would need some sense of organization, both so it
becomes easier to find your way around it (i.e., you know where to look when you're looking for something in particular) and so it
becomes easier for more than one person to work on it simultaneously without one person's changes stomping on another's. If two
pieces of relatively unrelated functionality are written in separate files (as they should be), then one person could work on one of
them while the other worked on another, and there would be much less chance of a conflict.
In this course, we're now reaching the point where our programs are large and complex enough that there is value in writing them
so they span multiple files, so we're going to begin to require that you do it, beginning in Project #2. But, in order to do that, you're
going to need to know a little more about how Python allows you to write and run programs made up of more than one file, and
you're going to need to start developing a sense of how best to decide what belongs in each file, and how to isolate unrelated
functionality so that changes in one file have the least likelihood of affecting the others.
What are modules?
A Python module is a file with a name ending in .py that contains a collection of definitions. Each definition establishes a name for
something — a function, a constant, or (as we'll see later this quarter) a class. So, for example, a module might be as simple as this
one:
powers.py
def square(n: 'number') -> 'number':
return n * n
def cube(n: 'number') -> 'number':
return n * n
You may previously have thought of .py files as containing Python programs, but if you load this particular module in IDLE and
execute it (by pressing F5), it'll appear that nothing has happened; you'll simply see a standard Python interpreter prompt, but no
other output. Yet it's not as though executing the module had no effect, because you'll now be able to call the functions defined in
that module:
>>> square(3)
9
>>> cube(4)
64
So there must be more to the story than we've discussed before. To understand what's happening here, there are a few more details
we need to be aware of.
Namespaces
A running Python program, particularly a large one, might have a very large number of names that it knows: the names of variables,
functions, parameters, constants, classes, and so on. When programs are very small, organizing these names isn't much of an issue;
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows pages 1-2 of the document.
Unlock all 5 pages and 3 million more documents.

Already have an account? Log in
variables can be global, all of your code can be in one module, and you can pay relatively little regard to organizational problems like
these:
How can I tell, given something's name, where I might find the code that defines it? (This isn't hard at all in a very small program, but
it becomes an issue when programs are much larger.)
What do I do if I want to use the same name more than once, but have it mean different things in different places? (This is a problem
that's less likely to come up in a very small program, but happens more often than you might think in larger ones.)
In Python, there isn't just one big global set of names. And, in fact, you probably know that already, because you've no doubt already
encountered the idea of scope in the context of functions. For example, consider these two fairly nonsensical functions:
def foo(n):
m = n + n
return m
def bar(m):
n = m + m
return n
When you look at these functions, you might notice that they both have one parameter and use one variable, each with opposite
names (i.e., foo calls its parameter n and its variable m, while bar calls its parameter m and its variable n). There are two key
questions we should consider here.
What effect does calling one function have when the other one is called subsequently? For example, foo stores a value in a variable
m. If we call foo and then call bar, what is the effect on bar's parameter called m?
What effect does calling either function have when we call the same function a second time? For example, bar stores a value in a
variable n. If we then call bar again, what value is in the variable n then?
The answer, as you've likely seen in previous coursework, is that in neither of these scenarios is one call affecting another. Every
time foo is called, it has a fresh parameter called n and a new local variable called m; bar is similar. We call these variables local
because they belong to a particular call to a particular function. And every time these functions return, its parameters and local
variables are destroyed, so subsequent calls to functions are unaffected.
What this tells us is that Python must already provide a way to organize its names, so it can differentiate between the names that
are local to one function and the names that are local to another. Python does this using what are called namespaces, which is a bit
broader than just isolating local variables between functions, though that is part of what they do. You can think of a namespace in
Python as a dictionary that maps names to the objects that have those names.
In general, the job of namespaces is to give meaning to a name that you use somewhere in a Python expression. For example,
consider this skeletal Python function:
def blah(...):
...
print(x)
...
When we ask to print the value of x, where is x? The answer is "It depends", and Python looks in a few places. (A few details have
been simplified here, but these are things that wouldn't affect programs written only using features we've learned so far.)
Python looks in the local scope first. If there's a local variable or parameter in this function called x, that's the x that gets printed.
Failing that, Python looks in the module's global scope next. In other words, it looks to see whether there is a global definition of x
(e.g., a global variable) in this module; if so, that's the x that gets printed.
Failing that, Python looks in the built-in scope next, which is to say that it checks whether there's a built-in definition — some
functions, like len() and open() are "built-in" in this way. If so, that's the x that gets printed.
Failing all of these, the attempt to print x fails by raising a NameError, since x is not defined anywhere that Python has looked.
Conspicuously absent from this list are other modules. How does code in one module use definitions in another? The answer is that
the other module must be imported first. You've probably seen the import statement in Python before, but may never have
considered what it actually does. But we've now reached the point where we need to understand it in more detail.
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows pages 1-2 of the document.
Unlock all 5 pages and 3 million more documents.

Already have an account? Log in

Document Summary

At a fundamental level, python programs are written in much the same way as programs in almost every other programming language in popular use: we write our code as text and store that text in files. You can learn a lot about python while writing only programs that are entirely stored in a single . py file, and there"s a pretty good chance that this is all you"ve done in your prior coursework. However, as programs grow beyond a certain size, it becomes important to split them up into separate files of a practical size, rather than writing them as one giant file. A python module is a file with a name ending in . py that contains a collection of definitions. Each definition establishes a name for something a function, a constant, or (as we"ll see later this quarter) a class.

Get access

Grade+20% off
$8 USD/m$10 USD/m
Billed $96 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers
Class+
$8 USD/m
Billed $96 USD annually
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
30 Verified Answers

Related Documents