473,385 Members | 1,958 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,385 software developers and data experts.

Import Semantics, or 'What's the scope of an import?', and classattribute instantiation

All,
I'm having some trouble with understanding python's importing behaviour
in my application. I'm using psyco to optimise part of my code, but I'm
not sure whether it inherits throughout the rest of my application (read
this as for any imported module) if I import in in a 'higher-level'
module. For example:

A.py
====

import psyco
from B import BClass
class AClass():
...
...
b = BClass()

B.py
====

class BClass():
...
...

In general, I've noticed that if import X and B in A.py and want to
reference X.* from B.py, I need to import X again in B. Is this a hard
and fast rule, or is there a way I can import the common libs, etc. in
the starting .py file and have those inherited by other classes I
import/instantiate? How would I do this?

It seems to be the general consensus that it's best to keep a Python app
in fewer files in the same directory rather than spreading them out, a
few (or one) classes to a file in a directory hierarchy as in Java. I
understand this is due to Python's, self.* and import <path> operations
having a relatively high cost (traversing directories, etc. etc.)

What I don't see mentioned is that when I step through a Python script
(say, in Eric3), if the structure of the file is like this:

X.py
====

class myX():
att1 = 'Test'
att2 = []
att3 = MemoryHungryClass()

class myY():
a = 'Another test'

....

if __name__ == 'main':
x = myX()

Python loads all the class attributes into memory (or, at least, cycles
through them) at runtime *even if I never instantiate the class*. This
has lead me to write code like:

class myX():
att3 = None
def __init__(self):
att3 = MemoryHungryClass()

Which seems to work a little better, but it seems rather ugly. I guess
the reason Python does this is because it's interpreted, not statically
compiled (and so needs to know whether myX.attr3 exists when called),
but I don't understand why the interpreter can't parse/instantiate the
attributes on the first call to instantiate the class. Surely this would
be a reason *for* splitting your code up into multiple files?

Being relatively new to Python, I'm trying to avoid coding things in an
un-Python (read C++/Java) manner, and am looking for some tutorials on
python-specific advanced features I can use (things like closures,
lambda forms, map(), etc. etc.). Could anyone point me towards some good
resources?

I would much appreciate some assistance in finding some answers to these
questions, as the research I've done seems to be inconclusive, if not
downright confusing.

Many thanks,
Andrew

--
Andrew James <dr**@gremlinhosting.com>

Jul 18 '05 #1
1 2357
Hi,
I'm having some trouble with understanding python's importing behaviour
in my application. I'm using psyco to optimise part of my code, but I'm
not sure whether it inherits throughout the rest of my application (read
this as for any imported module) if I import in in a 'higher-level'
module. For example:
In the psyco doc it says that you can do full() - but it will bloat the
memory consumption, so its better to use either explicit or profile-based
optimization. I suggest reading the docs for psyco on thate.
A.py
====

import psyco
from B import BClass
class AClass():
...
...
b = BClass()

B.py
====

class BClass():
...
...

In general, I've noticed that if import X and B in A.py and want to
reference X.* from B.py, I need to import X again in B. Is this a hard
and fast rule, or is there a way I can import the common libs, etc. in
the starting .py file and have those inherited by other classes I
import/instantiate? How would I do this?
No, you can't - and as you say later on that you come from java: That's not
possible there, either.

Generally speaking, for each unit/file for interpretation or compilation (in
java/c++), you have to import all names that should be known there.
It seems to be the general consensus that it's best to keep a Python app
in fewer files in the same directory rather than spreading them out, a
few (or one) classes to a file in a directory hierarchy as in Java. I
understand this is due to Python's, self.* and import <path> operations
having a relatively high cost (traversing directories, etc. etc.)
No - the cost for importing are not so high, and occur only once. A second
import will make python recognize that this module is already known, so it
won't be imported again.

So they don't add much to your runtime - only startup time. Which is still
way faster than java's....

Java simply limits you to one class per file so the can maintain a
bijektive .java <-> .class mapping. I guess for make-like dependency
checking.

And as in java the class is the only unit of code you can write, there is no
way to declare functions outside of classes. Which you can do in python.

If you really want to, you can go the way way java does it. But then you
have to manually update the __init__.py for a module to make all declared
names visible, like this:

foo/__init__.py
from A import A

foo/A.py
class A:
pass

This is of course somewhat tedious. Instead putting all classes and
functions directly into a file called foo.py will rid you of these
complications, and keep belonging code in one file.
Python loads all the class attributes into memory (or, at least, cycles
through them) at runtime *even if I never instantiate the class*. This
has lead me to write code like:

class myX():
att3 = None
def __init__(self):
att3 = MemoryHungryClass()

Which seems to work a little better, but it seems rather ugly. I guess
the reason Python does this is because it's interpreted, not statically
compiled (and so needs to know whether myX.attr3 exists when called),
but I don't understand why the interpreter can't parse/instantiate the
attributes on the first call to instantiate the class. Surely this would
be a reason *for* splitting your code up into multiple files?
I'm not totally sure that I understand what you are doing here - it seems to
me that you confuse class attributes with instance attributes. The latter
are (usually) created in the __init__-method, like this:

class Foo:
def __init__(self):
self.bar = 1
a = Foo()
b = Foo()
a.bar += 1

print a.bar, b.bar

yield 2 for a.bar and 1 for b.bar

The former are attributes created while importing (so far you're right), but
they are created only once - for the _class_, not the objects of that
class. So you can compare them to static properties in java. Which will
also be created at the first import, and consume whatever resources they
need - time- and memorywise.

You can of course instaniate them lazily - like this:

class Foo:
bar = None
def __init__(self):
if Foo.bar is None:
Foo.bar = SomeMemoryConsumingObject()

So bar gets filled only when you actually instantiate a Foo. But this is no
different from java:

class Foo {

static Bar bar = null;

public Foo() {
if (bar == null) {
bar = new SomeMemoryConsumingObject();
}
}
}
Being relatively new to Python, I'm trying to avoid coding things in an
un-Python (read C++/Java) manner, and am looking for some tutorials on
python-specific advanced features I can use (things like closures,
lambda forms, map(), etc. etc.). Could anyone point me towards some good
resources?


http://docs.python.org/tut/tut.html

Especially

http://docs.python.org/tut/node8.html

--
Regards,

Diez B. Roggisch
Jul 18 '05 #2

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

Similar topics

303
by: mike420 | last post by:
In the context of LATEX, some Pythonista asked what the big successes of Lisp were. I think there were at least three *big* successes. a. orbitz.com web site uses Lisp for algorithms, etc. b....
0
by: F. GEIGER | last post by:
Hi all, I use Leo for programming. Among other goodies Leo provides it let's me easily share code between different Python apps. When I have an app consisting of more than one file, they usually...
72
by: E. Robert Tisdale | last post by:
What makes a good C/C++ programmer? Would you be surprised if I told you that it has almost nothing to do with your knowledge of C or C++? There isn't much difference in productivity, for...
16
by: didier.doussaud | last post by:
I have a stange side effect in my project : in my project I need to write "gobal" to use global symbol : .... import math .... def f() : global math # necessary ?????? else next line...
23
by: Shane Hathaway | last post by:
Here's a heretical idea. I'd like a way to import modules at the point where I need the functionality, rather than remember to import ahead of time. This might eliminate a step in my coding...
27
by: v4vijayakumar | last post by:
what "enabling unwind semantics" occording to Microsoft (R) 32-bit C/C++ Optimizing Compiler. C:\Program Files\Microsoft Visual C++ Toolkit 2003\include\ostream(574) : warnin g C4530: C++...
49
by: Martin Unsal | last post by:
I'm using Python for what is becoming a sizeable project and I'm already running into problems organizing code and importing packages. I feel like the Python package system, in particular the...
12
by: Alan Isaac | last post by:
Are relative imports broken in 2.5? Directory ``temp`` contains:: __init__.py test1.py test2.py File contents: __init__.py and test2.py are empty test1.py contains a single line::
7
by: bambam | last post by:
import works in the main section of the module, but does not work as I hoped when run inside a function. That is, the modules import correctly, but are not visible to the enclosing (global)...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.