473,732 Members | 2,217 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 = MemoryHungryCla ss()

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 = MemoryHungryCla ss()

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**@gremlinho sting.com>

Jul 18 '05 #1
1 2379
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 = MemoryHungryCla ss()

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 = SomeMemoryConsu mingObject()

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 SomeMemoryConsu mingObject();
}
}
}
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
17695
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. Yahoo store was originally written in Lisp. c. Emacs The issues with these will probably come up, so I might as well mention them myself (which will also make this a more balanced
0
1024
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 do from other import AClassOfIt import yetanother When I then want to investigate a specific problem I share code with a
72
5881
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 example, between a C/C++ programmers with a few weeks of experience and a C/C++ programmer with years of experience. You don't really need to understand the subtle details or use the obscure features of either language
16
3112
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 generate an error message ?????
23
6416
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 process. Currently, my process is I change code and later scan my changes to make matching changes to the import statements. The scan step is error prone and time consuming. By importing inline, I'd be able to change code without the extra scan...
27
5968
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++ exception handler used, but unwind semantics are not enabled. Speci fy /EHsc
49
3936
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 isomorphism between filesystem and namespace, doesn't seem very well suited for big projects. However, I might not really understand the Pythonic way. I'm not sure if I have a specific question here, just a general plea for advice. 1) Namespace....
12
2738
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
2150
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) scope. Questions: (1) Where can I read an explanation of this? (2) Is there a work around?
0
8946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8774
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9447
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9307
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9181
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6031
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.