Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)

Thread Tools

[Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)

Alexander Blinne
Posts: n/a
At this point I think i could just refer to my other 2 postings and urge
you to read them again. They offer the idea of encapsulating the
function QuerySqlite into a method of an object that can be passed over
to some object (possibly throu the __init__-method) and store it in an
attribute of that other object. Those other objects can then simply call
the method belonging to the object.
If you really don't understand what I mean by this maybe you should
learn a bit about the basics of object-oriented programming.
Some pseudo-code illustrating this idea (which differs a bit from the
first singleton-like suggestion):

class Datastore(object):
def __init__(self, some_args):
#do all things needed to open datastore and store everything to
#self.something and self.someotherthing

def query(self, query, *values):
#execute query with values inserted
#using self.something and self.someotherting
#return result

class Modbus(self):
def __init__(self, datastore):
#store the argument datastore to an attribute of the newly
#created object
self.datastore = datastore

def read_bus(self, sensor):
#read from bus the value of sensor and return value

def read_temp_and_store(self, sensor):
#read and store
value = self.read_bus(sensor)
self.datastore.query("some query string", value)

class Scheduler(object):
def __init__(self, datastore, modbus):
#store the arguments datastore and modbus to attributes
#of the newly created object
self.datastore = datastore
self.modbus = modbus
#maybe read some config data from datastore
self.config = self.datastore.query("some initialising query if

def do_things(self):
#do things you wanna do, perhaps in some loop or in a thread or
#something, does not really matter.
#Threading may require locking of some kind, but this also is
#not really related to your problem as I understand ist.

from scheduler import Scheduler
from datastore import Datastore
from modbus import Modbus

def main():
datastore = Datastore(some_args)
modbus = Modbus(datastore)
scheduler = Scheduler(datastore, modbus)


if __name__=="__main__":

Please feel free to ask specific questions about this approach.

merry christmas everyone
Alexander Blinne
Reply With Quote
Dave Angel
Posts: n/a
On 12/24/2012 03:23 AM, Removed) wrote:
> Hello Dave,
> Thank you, for your help, I'll try my best.
> To all others, PLEASE be pleasant with my nescience, I'll tried to describe not a specific error at my Program. I'll tried to get rid of that missing link this sample is only theoretic, but the code really exists and is over 1000 lines long.
> I understood how to transmit data to a class,

This is an example where terminology is messing up communication. To me,
transmission implies communication between two different active systems,
like across a network, or at least between processes. A class isn't
active at all, it's a holding place for attributes (class-attributes),
and it's indirectly a description of what instances will look like.
Most likely what you mean is you know how to pass data to an instance
method of a class. Or how to set class-attributes, or
instance-attributes, which are not the same thing.

> but I do not understood how that class could access an SQL object, that is allready opened at a other class without getting into troubles with sqlite.

I don't know sqlite, so I don't know what might constitute 'getting into
troubles.' But a class method (not the class itself) is given a self
object, and other parameters, and if one of those parameters is an SQL
object, it can be manipulated there just as readily as wherever that SQL
object was first discovered.
> For my understood, the newsgroup isn't a place only to solve concrete problems. I think you're not only a "helpdesk" , If I'm at the wrong group to get some Ideas how to solve my "issues"

We're a disjoint bunch of volunteer teachers, and a bunch of learners,
and each of us spends some of our time in each role. Most people spend
quite a while "learning," or at least lurking, before asking questions.
Then a bunch more before being ready to answer questions and make useful
comments. But it's not a linear process, and nobody takes a test to
qualify for "teaching." The goal of this forum is to field the
questions which are above the level of python-tutor.

More importantly than the "purpose" of the forum is that the nature of a
forum is that you have to get the interest of enough readers that
somebody knowledgeable about your problem will actually jump in and help
solve it. There are a number of ways to discourage useful responses,
and one of them is to write confusing comments or non-working code. Of
course, confusing phrasing can be a language issue, or it can be an
understanding issue. But it's easy to tell when there's non-working
code. If it doesn't run, it's not working. Is that a problem? Depends
on the nature of the question.

> Ps.: DaveA I don't know how to say it, but I treasure your great work here, giving such detailed good answers.

To the others, he's referring in part to an offline apology, where I
offered some detailed suggestions.

> PPs.: I know, that my codingstyle isn't that great, I've haven't programmed the last two years. You're welcome to guess what I've worked 8 years long. you will laugh till you fall of your keyboard
> PPPs.: I' will use that day to check out the PEP's and correct my coding style, and naming.
describes coding guidelines. But please note that the places where
I was correcting your capitalization, it was only a small part of pep8,
the parts which are most likely to be causing confusion between you and
us. It's important to get your mind around the differences between
modules, classes, instances, attributes, etc., and when we use the
appropriate capitalization, it tends to show we're understanding it.

There are other things in pep8 that haven't been mentioned here, and
there are many things I don't follow. But for example I use 4 spaces
for indenting, and never tabs. Some people prefer tabs, and python
permits it. But mixing them is real hazardous, since code may seem to
be doing one thing and actually do another if the way you expand the
tabs is different than the way the compiler does. But the real problem
online is that your tabs may work great with your toolset, but once you
put it in a message, they may work entirely differently to the hundreds
of different toolsets we use to view and/or try out your code.

Pep8 recommends a particular style within a function name, separating
'words of a name by underscore. I happen to loathe that style, so I'm
clearly not the one who would critique someone for not following the
guideline. I say getFile(), the pep says get_file().

Anyway, Pep8 is a guideline.

I think you need a tutorial, badly. Two years of not programming is no
big deal, but you don't seem to understand a number of very fundamental
concepts, or at least not understand them well enough to express them.
The real question is probably what other language did you use, and were
you a master at it, or just dabble. No offense intended, you've never
said whether this is your primary career, nor how old you are, nor any
other thing which might let us guess.

I like software, (though I took 8 years off to run a photography
business (and moonlighted about 3 years of the time to supplement the
income). But I insist on creating a useful mental model of how a
language and/or system operates. Then I modify that model when things
prove to be wrong. So a tutorial that might be good for me might not be
the right one for you. The two that I'd suggest are: - the official one - Alan Gauld's tutorial. I don't know it, I
just see how much help Alan is here and elsewhere, and Assume the
tutorial is similar

I'm going to continue in another message later, trying to do a "jump in
the middle and answer some questions which may have been asked, or
should have, or something."



Reply With Quote
Dave Angel
Posts: n/a
Python is a flexible language, but manages to let one write readable
code even while using that flexibility. It does, however, require that
one gets a grasp of some concepts that may differ greatly, either in
implementation or in name, from other languages. Every language has its
quirks and constraints, but Python is usually about self-discipline,
rather than the language forcing it down our throat.

So you can write object-oriented code, or you can (for the most part)
forget that objects exist, and use them without realizing. You can
write functional code (mostly), or you can ignore that concept. The
main thing I can think of that you can't do is "goto." Unlike C,
BASIC, and assembler.

Python 2.7, if not stated otherwise. 3.x has some new rules. I'm going
to assume you're familiar with lots of concepts, and have played with
the language. So I'm not going to define print, or the plus sign.

So what are the building blocks? Everything in Python is an object, or
becomes one soon after you look at it. Open a file, you get an object.
Do some arithmetic, you get an object.

So how do you create one? As soon as you launch the compiler on your
source script, you're creating a module object. inside that module
object are attributes that we usually call global variables, and other
attributes we call functions. And maybe attributes we call classes.
These are creating while compiling that script. How do we reference
those objects? By using their names. That's what's meant by global,
they're universally accessible. Oops, that's until we start making more
modules, which we'll get to later.

Python also has a bunch of modules it already loaded for us, including
the one called builtins. Those objects appear magically in every
module, so they appear global as well. What about objects in some
library function? First we have to import the module, then we reference
the object by both the module name and the name in THAT global space.
(That's why the word global was probably unfortunate). So to get at the
function object called "sin" in the module called "math", we do the
following two statements:

import math
print math.sin(1)

What did that import do? It simply created a new global called math,
and bound it to the module by that name, compiling it and loading it if
necessary. Once we have imported it, we can use ALL of its globals
(functions, variables, and classes, mostly) simply by the magic of the
dot. math.sin means look up the global math, then within that object
look up the attribute sin. The syntax doesn't care that math is a
module, the same syntax would work if math was a file you just opened,
and sin was a File method. So to read data from a file, we might do

myfile = open("filename")

Now, we glibly used 1,10, and "filename" in the above. What are they?
They're literal objects. In the source code you give enough information
to create an object of a particular builtin type (like int and str), and
by the time the code is running, these objects are created in some
magical space we might call "the literal pool." How that works doesn't
matter to anybody except to the guys building the compiler/interpreter.

So some names are global, and some are attributes. I think that's it
for names. There are constraints on what characters make up a name
(though in 3.x, that restricts one to a few hundred thousand symbols or
so), but that's about it.

Do all objects have names? Nope. We also have the notion of
containers, and we have special syntax to access them. So a list can
reference dozens, or millions of objects, and none of them have an
independent name. And the list might not either, if it came from a
literal print [1,2,3].

What about a dictionary. Funny thing, a dictionary works much like
attributes, only with a special syntax, and no restrictions on what the
keys can be. In fact, under the covers, attributes are just items in an
invisible dictionary of an ordinary object. (Note that invisible means
you don't usually care, in Python it's nearly always possible to peek
through the keyhole to see these things, but it can be very confusing,
and even harder to discuss)

Now we've been glibly referring to global items "having values" and
attributes "having values" and in fact much of the literature refers to
variables. But in a real sense, there are no variables at all. There
is what's called binding. A name is bound to an object. Any object,
created any way, and located any way. A list entry is bound to an
object. So the object itself has no name. it has type, and it probably
has attributes (actually it always does, but they may be "invisible").
But a name might be bound to that object at some time, or ten names, or
none at all. And the object (probably) ceases to exist once there's no
way to find it. If it's been bound to three names, and you rebind all
three names, then the object goes away after the third name is rebound.
If its bound to a slot in a list, and also in a dictionary, and also in
a name, then it won't go away till all of those go away, or get rebound.

An important concept is mutation. Many object, such as ints and strs,
are immutable, meaning they cannot change. You can create a new object
very similar to the original, and rebind names from first to the second:
a = "Peter"
a = a + " Punkin Eater"

So a is rebound to a new object, and the Peter object will go away.

But if we have a mutable object, like a list, then we can modify the
single object without having to rebind it.
a = [1,2,3]

This "changed a" but not really. It changed the object that a is bound
to. This distinction is a primary reason why the term variable is

Now I get to modules, which are really most interesting when you start
writing the yourself. Then, instead of following examples in the module
description, you have to decide how the module's "public" interfaces are
going to work, and why.

Back to the example
import math
print math.sin(1)

Suppose that we use that function a lot. Then we might wish to avoid
prepending it with the module name every time. The direct way to do
that is simply
sin = math.sin

This creates a new global name, and binds it to the object which was
already accessible as math.sin . Notice that there are now two ways to
get at that function, and also notice that we have no called the
function yet (no parentheses).

The shorthand for this is
from math import sin

It does the same thing, but without actually defining a global called math.

Please avoid the funny mechanism: from math import * It gives the
reader no clue as to what symbols are now visible as globals. And some
of those symbols might happen to have names that conflict with others we
do want. The only time to do this is when a module is specifically
designed that way. it can be coded in such a way as to restrict the
names that come in. I still don't like it, but the docs are probably
written that way.

So if you write your own, please use a lowercase leading letter in the

Now, to reference stuff in that other module, you add an import, just
like you did with math.
import mymodule
result = mymodule.myfunction(arg1, arg2)

Let's assume you use
from mymodule import myfunction

You now have an extra name bound to the same object as myfunction was in
the other module.

For constants and for functions, this is pretty straightforward. But
what happens if somebody changes one of those globals? that depends if
they rebind it, or they mutate it? If they rebind it, you'll still be
referring to the original version. While if they mutate it, you'll see
the changes, because you have an extra name bound to the same object.

I haven't mentioned writing classes yet, and describing them will take
lots more words.



Reply With Quote
Dave Angel
Posts: n/a
(Part 3 of my dissertation; I hope it's useful for you in particular)

Up to now in my discussion, it wasn't usually important to know that
everything is a class. You just know that everything has attributes,
and that you use the dot notation to get at an attribute. So what if
"%x".format() is a class method of the class str, you can just learn
"this is how you can format text". But once you learn how to write
classes, it starts to all come together.

class MyClass (myParentClass):

This line, and all indented lines below it, constitute a class. The
defs inside are functions, but they're also methods, with special
behavior of the first parameter, called 'self' by convention. So a def
might look like:
def myMethod(self, arg1):
return arg1 * 2

Now, if somebody has an instance of your class, they can call this
method like:
and the return value will be 84. This is remarkably like the notation
we used before inside a module. So a class *could* be used just to
encode the namespace. But the power comes when there are attributes on
the object, and when self is used to get at those attributes. In that
situation, the self can refer to all kinds of data. In a sense you
could think of that data as being like the globals of a module, except
for one very important thing. There's only one instance of the module,
so those globals are shared between everyone. But with an instance, you
can have many instances, and each has its own set of attributes.

Simplest way to illustrate this is with a MyFile class. There's already
a very nice class in the standard library, with a builtin function
open() to create a new instance. But we can pretend to write such a
class, and see how making it a class is probably better than any other
way to code the functionality. And in fact, many people have done
something like that, to reference something analogous to a file.

When we open a class, some code somewhere has to keep track of the
system's file handle, the file position, the mode of operation, any
buffers that might be used, etc. Whatever that data is, if it's kept in
an instance, then it's possible to open multiple files at the same time,
some for writing, some for reading, etc. So how might we go about doing

class MyFile(object):
def __init__(self, filename, mode):
self.filename = filename #remember the filename, in case
someone wants it
self.handle = someOScall(filename, mode) #do whatever it
might take to actually open a file
self.position = 0
self.opened = True
def read(self, size):
data = someOScallToRead(self.handle, self.size) #do whatever
it takes to read some data
self.position += size #probably it's more
complicated than this
return data

Now __init__() is a special method name. It's called implicitly when an
object of this class is made. A newly created dummy object of the right
type is passed to __init__() as self, and we want to stuff that object
with the appropriate attributes (typically a dozen or more).

read() is a simple method, although it could be *much* more complex for
a real file. It might do buffering, or it might translate characters,
or almost anything. But by the time it's called, we know the object's
__init__() method has been called, a file is open, the handle
initialized, etc.

So now the user can create two different objects:
file1 = MyFile("firstfile.txt", 12)
file2 = MyFile("otherdirectory/secondfile.txt", 49)

and can unambiguously read from whichever one she likes.

This notion that the attributes of the object carries all its necessary
data, and that the user of the class need not know any of the details is
the reason one can readily write code in separate modules that knows
little about the internals. Just pass the necessary object around, and
if the class was done right, it'll be ready to do all the operations
defined on it.

Hope this helps. It's just barely scratched the surface of what's possible.



Reply With Quote
Ranting Rick
Posts: n/a
On Dec 24, 9:48*am, Dave Angel <(E-Mail Removed)> wrote:
> Pep8 recommends a particular style within a function name, separating
> 'words of a name by underscore. *I happen to loathe that style, so I'm
> clearly not the one who would critique someone for not following the
> guideline. *I say getFile(), the pep says *get_file().

Slightly off topic, but still quite relevant: I happen to like that
style for public methods (even though Python has no real public/
private methods).

class Foo():
def __init__(self)
def __secretMethod() # Secret handshake required!
def _privateMethodOrAccessor() # Self only.
def sharedMethod() # Self and/or descendants only.
def public_method() # Total whore.
Reply With Quote
Posts: n/a
Hey I think I should rename the threads name into a new "Doc" project,
I'm sure It won't take much time to fill a book with our knowledge.

Thanks to Rick, you have Posted exactly what I wanted to ask. I know the that
__variable = 'xyz'
_variable = 'xyz'

are used to make them private, but I haven't found it for methods. Thanks

I also don't think you're off topic! It's a big grey scale and for me the first post till the last one is a part of my "question"

PEP, is nice, it tooks me a few days to get trough all your input and my code. Anyway is there also a best practice for naming? eg.: module_class_sub() or wording? eg.: socket: send() recv() -> recv is kept short. according PEP8??

It seems, my english slowly getting better again, If my colleagues would see what I'm writting here they won't belive me. I've worked at the Pharmaceutical IT and made Codereviews and programming for medical software. I stillcan't belive what I've forgotton the last two years. But still PEP etc. isn't far that hard written like pharm eu, usp, and 21CFR. Shame on me, but Iwill come back, after I've finished.

Reply With Quote
Posts: n/a
Hello Steven,

to "learn python" I've bought a book, and it's not a "thin" one it's more a 788p. long documentation about python.

BUT!!!!! I have to say: The autor started using the "self." argument at the chapter classes. So You've shown me the book descr. non "correct" way. Better using this book heating my home?!

Reply With Quote
Dave Angel
Posts: n/a
On 12/25/2012 09:41 AM, (E-Mail Removed) wrote:
> Hello Steven,
> to "learn python" I've bought a book, and it's not a "thin" one it's more a 788p. long documentation about python.
> BUT!!!!! I have to say: The autor started using the "self." argument at the chapter classes. So You've shown me the book descr. non "correct" way. Better using this book heating my home?!
> Patrick

You still are being imprecise. You don't give a title or author, and
you refer to the "chapter classes" whatever that is. Do you mean the
chapter about classes? If so, that's exactly where 'self' should be

How about copying an example function that uses self, that you think is
incorrect ? If it is incorrect, perhaps we should give the author some

We all make mistakes, like my referring to class methods when I meant
instance methods. But I didn't figure it was time to introduce class
methods, so I wasn't trying to make the distinction. My error.



Reply With Quote
Posts: n/a
By the way i haven't add the Title because it's a german only book named
"Python 3: Das umfangreiche Handbuch, Published by Galileo Computing"

and also, because I've registered to first check if the Autor has allready published a update. Too many information's could ocurre in an avalanche

I see a big failure:

1. I answer to quick

Reply With Quote
Posts: n/a
By the way i haven't add the Title because it's a german only book named
"Python 3: Das umfangreiche Handbuch, Published by Galileo Computing"

and also, because I've registered to first check if the Autor has allready published a update. Too many information's could ocurre in an avalanche

I see a big failure:

1. I answer to quick

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: migrating from python 2.4 to python 2.6 Mark Lawrence Python 0 07-09-2012 11:05 AM
Tabnanny errors when Migrating Python 2.4 code to 2.5 Python 3 01-04-2008 10:28 PM
advice required re migrating php app to python and most likely zope Ken Guest Python 2 01-06-2006 10:59 AM
migrating c code to perl chetan Perl Misc 3 01-13-2004 06:35 AM
Perl Help - Windows Perl script accessing a Unix perl Script dpackwood Perl 3 09-30-2003 02:56 AM