473,396 Members | 1,982 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Scope and program structure problems

Trying to learn Python here, but getting tangled up with variable
scope across functions, modules etc and associated problems. Can
anyone advise please?

Learning project is a GUI-based (wxPython) Python program that needs
to access external data across a serial port.

The first thing that I need the program to do when it starts up is to
check that it can see the serial port, the first step of which is to
check that it can import the pySerial module, and display an
appropriate message in the statusbar of the main frame. (I know there
may be other ways of doing this but this is what I'm trying to do
currently and I'd like to understand how to make this approach work
robustly even if there are other options.)

So it seems that if I want to write to the frame's statusbar, I can't
do anything re serial import until the frame is initialising. And I
can't put any serial import code after the app.Mainloop() code line
because it won't run until the frame closes.

In other words, I seem to be stuck with importing the serial library
either in the __init__ function or - if implemented slightly
differently - in a separate function of the wxPython Frame class, ie a
code structure of:

-----------
# Can't put serial import code here because there's no GUI yet to send
messages to.

Class Frame(wx.Frame)
def __init__()
etc
#code to check and use serial port has to go below??
def CheckSerial() # eg triggered by appropriate menu click event
Try:
import serial
etc
ser = Serial.etc # set ser object as handle to serial port
def UseSerial():
# Code to perform serial IO

app=App(wx.App)
app.MainLoop()

# Can't put serial import code here because it won't execute until
frame closes?
-----------

But then I hit another problem. If I set the object ser to point to
the serial port in the CheckSerial function, then it's just got local
scope within the function and can't be seen from the UseSerial
function.

So I've got 2 questions. The main one is whether there's any way of
explicitly giving the ser object global scope in the code line:

ser = Serial.etc # set ser object as handle to serial port

And, second, does my overall description above reveal any serious
misunderstanding about how best to handle this sort of problem in
Python?

Apologies for the long post and hope that my description is clear
enough to make sense.

JGD
Jul 1 '08 #1
3 2446
John Dann a écrit :
Trying to learn Python here, but getting tangled up with variable
scope across functions, modules etc and associated problems. Can
anyone advise please?

Learning project is a GUI-based (wxPython) Python program that needs
to access external data across a serial port.

The first thing that I need the program to do when it starts up is to
check that it can see the serial port, the first step of which is to
check that it can import the pySerial module, and display an
appropriate message in the statusbar of the main frame. (I know there
may be other ways of doing this but this is what I'm trying to do
currently and I'd like to understand how to make this approach work
robustly even if there are other options.)
(snip)
>
-----------
# Can't put serial import code here because there's no GUI yet to send
messages to.

Class Frame(wx.Frame)
def __init__()
etc
#code to check and use serial port has to go below??
def CheckSerial() # eg triggered by appropriate menu click event
Try:
import serial
etc
ser = Serial.etc # set ser object as handle to serial port
def UseSerial():
# Code to perform serial IO

app=App(wx.App)
app.MainLoop()

# Can't put serial import code here because it won't execute until
frame closes?
-----------

But then I hit another problem. If I set the object ser to point to
the serial port in the CheckSerial function, then it's just got local
scope within the function and can't be seen from the UseSerial
function.

So I've got 2 questions. The main one is whether there's any way of
explicitly giving the ser object global scope in the code line:

ser = Serial.etc # set ser object as handle to serial port
It is possible - for the python definition of 'global' being
'module-global' - but it's not necessarily the best solution. Look up
the doc for the 'global' statement to learn more.

Another solution would be to make ser an attribute of your Frame object:

class Frame(wx.Frame):
def __init__(self):
self.serial = None

#code to check and use serial port has to go below??
def setup_serial(self) # eg triggered by appropriate menu click event
try:
import serial
except ImportError, e:
# display an error message and either crash
# or return

else:
# set self.serial object as handle to serial port
self.serial = serial.etc()
def use_serial(self):
# Code to perform serial IO
# won't work if setupSerial failed
And, second, does my overall description above reveal any serious
misunderstanding about how best to handle this sort of problem in
Python?
Well... You'd get a very similar result by doing your import at the
top-level but within a try/except block, then when you have a gui setup
takes appropriate actions.

try:
import serial
serial_import_error = None
except ImportError, e:
serial = None
serial_import_error = e
class Frame(wx.Frame):
def __init__(self):
self.serial = None

def setup_serial(self):
if serial is None:
# display an error message and either crash
# or return
else:
self.serial = serial.whatever()

<disclaimer>

But anyway: I have no real (read : anything requiring any brain-cell)
experience writing rich GUI apps in Python, and I haven't done rich GUI
programming for four last years at least, so there may be better
solutions here.

So : Any wxPython guru around ?-)

</disclaimer>
Jul 1 '08 #2
Many thanks for the repsonse - much appreciated.

And sorry - yes I was probably compounding two separate issues here -
the GUI one and the variable scope one. Maybe the wxPython list would
be the best place to ask more about the GUI side of things.

Then actually I can simplify my remaining question quite a lot - I
know you've partly answered this already but let me just rephrase
this:

It must be commonplace to first use a variable or object within one
function in a module and then want to use it again - perhaps still
with the same value as in the first function - in a second function.

So what's the recommended Python way round this? If I was using .Net
then I'd be declaring the variables/objects explicitly and could set
their scope according to how/where they were declared. But if the
Python way is not to declare vars before use then this must create
some problems for cross-function use.

So it is best to declare such vars at the module level (ie outside of
a function) and set eg to Null/None or to assign them with a keyword
such as global or static (assuming that concept applies in Python) at
first use inside a function or what?

JGD
Jul 1 '08 #3
John Dann a écrit :
Many thanks for the repsonse - much appreciated.

And sorry - yes I was probably compounding two separate issues here -
the GUI one and the variable scope one. Maybe the wxPython list would
be the best place to ask more about the GUI side of things.

Then actually I can simplify my remaining question quite a lot - I
know you've partly answered this already but let me just rephrase
this:

It must be commonplace to first use a variable or object
What difference do you make between a variable and an object in this
context ?
within one
function in a module and then want to use it again - perhaps still
with the same value
For which definition of "same value" ? Remember, Python has *no*
primitive types. Everything is an object.
as in the first function - in a second function.
So what's the recommended Python way round this?
This is way too general to give a single straight answer - whatever the
language FWIW. Are both function in the same module ? Are they methods
of a same object ? Is the first function calling the second or are they
totally unrelated ?
If I was using .Net
then I'd be declaring the variables/objects explicitly
I personnally find the assignment, import, class and def statements (all
having a binding behaviour) to be rather explicit.
and could set
their scope according to how/where they were declared.
Names bound at the top-level are globals to the module. Names bound
within a function (including arguments) are locals, unless there has
been a global statement for them before in the same function's body.
Names bound within a class statement lives in the class's namespace (IOW
: they become class attributes, shared by all instances). And names
bound as object attributes (using either obj.name = whatever or
setattr(obj, "name", whatever)) become, well, object attributes.

Now there may be a couple points worth paying attention to :

1/ some types (numerics, strings and tuples at least) are immutable.
When doing :

i = 1
i = 2

the second assignment doesnt mutate the integer object bound to i, but
rebinds i to another integer object.

2/ the scope of a name isn't necessarily related to the scope of the
object bound to that name.

As an example, function's parameters *names* are local to the function,
but the actual arguments - the objects passed when calling the function
- are not.

IOW, rebinding a parameter name withing a function body will rebind the
name locally, but will not affect the object originally bound to that
name. But *mutating* an object passed as argument *will* (off course)
affect the object outside the function.

But if the
Python way is not to declare vars before use
For which definition of "var" and "use" ? Did you really try to use a
name that didn't exist in the accessible namespace - I mean, "use" for
anything else than binding ?

The first binding of a name in a namespace *is* the 'declaration'. If a
name is not defined in the currently accessible namespace, and you try
to do anything else than binding it, you'll get an exception.
then this must create
some problems for cross-function use.
If what you mean is that it makes it harder to litter you code with true
global variables, then it's obviously a *very* good thing IMHO !-)

But no, there's no more problem with shared state in Python than in any
other (imperative) language I know - usually less in fact since there's
no "application global" namespace. Most of the time, the appropriate way
to share state is to use classes - heck, that's what they were created
for, isn't it ?-). Sharing state thru module-level variables is ok as
long you only access it for reading (pseudo-constants etc).

Sometimes, it's ok to use a module-level variable read-write, but this
should be restricted to this particular module's implementation stuff
(IOW : the name is not part of the API, and only functions / methods in
this same module access it), and never done without a clear enough
understanding of Python's namespaces and bindings.

So it is best to declare such vars at the module level (ie outside of
a function) and set eg to Null/None or to assign them with a keyword
such as global or static (assuming that concept applies in Python)
it doesnt.
at first use inside a function or what?
Usually, when you really need a module-level variable to be shared
read-write between functions, it happens that you can bind it to a
sensible default. Now what is a "sensible default" depends on the
concrete use case. Anyway, by all means, explicitely bind this name at
the top-level, before any code accessing it, and if possible with a
comment about this name being shared read/write by functions x and y.

My 2 cents...

Jul 1 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: alphatan | last post by:
Is there relative source or document for this purpose? I've searched the index of "Mastering Regular Expression", but cannot get the useful information for C. Thanks in advanced. -- Learning...
5
by: pembed2003 | last post by:
Hi all, I am reading the book "C How to Program" and in the chapter where it discuss scope rule, it says there are four scopes for a variable: function scope file scope block scope...
3
by: marco_segurini | last post by:
Hi, I am using VS 2005. If I compile the following code only line 6 returns me an error while line 9 returns a warning. If I comment the line 6 and debug the program the assignments of lines...
7
by: moondaddy | last post by:
I want to create a public enum that can be used throughout a project. I created an enum like this in a module: Public Enum ParentType Project = 0 Stage = 1 VIP = 2 Func = 3 Equipment = 4...
165
by: Dieter | last post by:
Hi. In the snippet of code below, I'm trying to understand why when the struct dirent ** namelist is declared with "file" scope, I don't have a problem freeing the allocated memory. But...
5
by: rick | last post by:
I'm working on a disassembler for a school project. Things work but I get compiler warnings as follows: cc -W -Wall -pedantic -ansi main.c defs.h:44: warning: 'blah' defined but not used blah...
4
by: AndrewD | last post by:
Hey C++ folks, I created this today, just for fun. You can make object allocation for any class around 6 times faster, simply by doing the following. class MyClass : public...
2
by: Laurent Deniau | last post by:
I would like to know why the following small program does not compile (checked with gcc 4.1.2) and if the compiler behavior is correct: struct A; typedef void (T)(struct A*); void f(void) {...
1
by: Giacomo Catenazzi | last post by:
Hello, To learn the details of C, I've build the following example, could you check if it is correct and if it miss some important cases? Are there some useful (real cases) examples of: -...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.