Hi people,
I wonder why the isinstance() function is sensitive about the import
path i.e. the result depends not only on the class and the instance but
also on how a class is imported?
Example:
MyPackage/ Top-level package
__init__.py Initialize package
__me__.py Module used for setting Python-path
A.py Use objects of ForeignPackage and
subpackages
ForeignPackage/ Don't touch!
__init__.py Initialize package
B.py Defines class B1
MySubPackage/ Subpackage
__init__.py Initialize subpackage
C.py Defines instance checker for B1 instances
Provide some implementations :
_______________ _______________ _______________ _______________ _______________ __
# MyPackage.__ini t__.py
import __me__
__me__.setmypat h()
# MyPackage.__me_ _.py
def setmypath():
import __me__
import inspect
import sys
absfile = inspect.getabsf ile(__me__)
abspath =
"/".join(absfile. split("/")[:-1]+absfile.split( "\\")[:-1])
sys.path.append (abspath)
# MyPackage.A.py
from MySubPackage.C import*
from ForeignPackage. B import*
b1 = B1()
checkInstance(b 1)
#print b1.__class__
# MyPackage.Forei gnPackage.__ini t__.py
# left empty
# MyPackage.Forei gnPackage.B.py
class B1(object):
def __init__(self): pass
# MyPackage.MySub Package.C.py
import MyPackage
import ForeignPackage. B as B
#import MyPackage.Forei gnPackage.B as B
def checkInstance(i nst):
if isinstance(inst ,B.B1):
print "class is %s"%inst.__clas s__
else:
raise TypeError,"Inst ance of unknown class '%s'
found"%inst.__c lass__
_______________ _______________ _______________ _______________ _______________ _
No run A.py :
A will call checkInstance with a B1 instance and prints
"class is <class 'MySubPackage.B .B1'>"
as expected.
But if one comments in the line
import MyPackage.Forei gnPackage.B as B
in module C.py and calls A.py one gets:
Traceback (most recent call last):
....
TypeError: Instance of unknown class '<class 'ForeignPackage .B.B1'>'
found
The class which was expected by the checkInstance() function is
<class 'MyPackage.Fore ignPackage.B.B1 '>
I'm curios if someone could explain me the difference between this two
class objects?
Regards,
Kay 4 1526
Kay Schluehr wrote: I wonder why the isinstance() function is sensitive about the import path i.e. the result depends not only on the class and the instance but also on how a class is imported?
isinstance uses class object identity.
if you manage to import the same thing multiple times, you'll have
multiple class objects representing the same source code, and is-
instance won't work properly.
Example:
MyPackage/ Top-level package __init__.py Initialize package __me__.py Module used for setting Python-path A.py Use objects of ForeignPackage and subpackages ForeignPackage/ Don't touch! __init__.py Initialize package B.py Defines class B1 MySubPackage/ Subpackage __init__.py Initialize subpackage C.py Defines instance checker for B1 instances
in my newsreader, it looks like the C.py module is defined some-
where inbetween MyPackage and MyPackage/ForeignPackage.
what file system are you using? ;-)
(I don't have the energy to decipher your convoluted import
and path-manipulation code; but my intuition tells me that if
you flatten the hierarchy, put MyPackage and ForeignPackage
at the same level, and stop messing with the path inside the
__init__ files, your problems will just disappear).
</F>
Fredrik Lundh wrote: Kay Schluehr wrote:
I wonder why the isinstance() function is sensitive about the
import path i.e. the result depends not only on the class and the instance
but also on how a class is imported? isinstance uses class object identity.
if you manage to import the same thing multiple times, you'll have multiple class objects representing the same source code, and is- instance won't work properly.
Importing a class/module multiple times does not cause the problem.
Writing
import ForeignPackage. B as B1
import ForeignPackage. B as B2
in C.py does not destroy the identity B1 == B2. Perhaps it is recovered
from sys.modules["ForeignPackage .B"]? It is not actually isinstance()
that depends on path information but the module recovery. The importer
seems to disambiguate to greedy. Example:
MyPackage/ Top-level package __init__.py Initialize package __me__.py Module used for setting Python-path A.py Use objects of ForeignPackage and subpackages ForeignPackage/ Don't touch! __init__.py Initialize package B.py Defines class B1 MySubPackage/ Subpackage __init__.py Initialize subpackage C.py Defines instance checker for B1 instances in my newsreader, it looks like the C.py module is defined some- where inbetween MyPackage and MyPackage/ForeignPackage. what file system are you using? ;-)
This is surprisingly irrelevant. I used __me__.py for several projects
under Win2K without harm. Python seems to be more intelligent in path
handling than Windows.
(I don't have the energy to decipher your convoluted import and path-manipulation code; but my intuition tells me that if you flatten the hierarchy, put MyPackage and ForeignPackage at the same level, and stop messing with the path inside the __init__ files, your problems will just disappear).
Flattening the package structure would solve the problem as well as
destroying all file-system based packages and abandon them from Python.
A bad joke? Yes, but managing all code using a database instaed of an
OS dependent filesys would make sense to me.
Ciao,
Kay
Kay Schluehr wrote: if you manage to import the same thing multiple times, you'll have multiple class objects representing the same source code, and is- instance won't work properly. Importing a class/module multiple times does not cause the problem. Writing
import ForeignPackage. B as B1 import ForeignPackage. B as B2
that doesn't import it more than once; Python uses a cache to hold
modules, but the cache only works if Python can be sure that the
modules are the same thing, based on the information in the *import*
statement. in this case, "ForeignPackage .B" is clearly the same thing
as "ForeignPackage .B".
if you change the path around (in your case, by adding MyPackage to
the path, rather than relying on path-relative import), you'll introduce
multiple ways to import the same module, and the cache won't work
properly. and when the cache doesn't work, isinstance breaks down
for the reason I stated.
Flattening the package structure would solve the problem as well as destroying all file-system based packages and abandon them from Python.
well, packages for just fine for me. if you cannot get them to work,
maybe you should stop doing things that don't work.
</F>
Fredrik Lundh wrote: Kay Schluehr wrote:
if you manage to import the same thing multiple times, you'll
have multiple class objects representing the same source code, and is- instance won't work properly. Importing a class/module multiple times does not cause the problem. Writing
import ForeignPackage. B as B1 import ForeignPackage. B as B2
that doesn't import it more than once; Python uses a cache to hold modules, but the cache only works if Python can be sure that the modules are the same thing, based on the information in the *import* statement. in this case, "ForeignPackage .B" is clearly the same
thing as "ForeignPackage .B".
Yes, that's what I did expect.
if you change the path around (in your case, by adding MyPackage to the path, rather than relying on path-relative import), you'll
introduce multiple ways to import the same module, and the cache won't work properly. and when the cache doesn't work, isinstance breaks down for the reason I stated.
Exactly. "ForeignPackage .B" and "MyPackage.Fore ignPackage.B" are two
paths pointing to the same module but it will be imported twice because
the cache does not lookup a strong name ( e.g. a hash of the module )
but the import path. This may also be the reason why it is not possible
to import a module in an interactive session, than edit it and finally
re-import it into the same running session. The hash value would have
been changed but the path remains the same. Flattening the package structure would solve the problem as well as destroying all file-system based packages and abandon them from
Python. well, packages for just fine for me.
In some cases they do, in other they don't. The __me__.py module comes
from working with ClearCase where the Python package is not installed
by an installation routine relative to an existing Python path. The
package has to recognize it's own position somewhere relative to the
virtual directory which can be arbitrary. Installing the package under
site-packages/ is a no go.
if you cannot get them to work, maybe you should stop doing things that don't work.
For shure, but people tend to do workarounds. So I did.
Regards,
Kay This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Mark Fisher |
last post by:
I have a Java desktop GUI application that the user can run multiple
times. In order to keep one instance of the application distinct from
another, I'd like to put the instance number of the application in the
title bar.
For example, the user starts the application, and the title bar says
"Control Panel". The user starts another instance of the application,
and it knows that one instance is already running, so the title bar of
the...
|
by: Carlos Ribeiro |
last post by:
I am looking for information on packages & import hooks, including
simple examples on how to implement a simple import hook. Quick
googling turns out some documents, such as:
-- PEP 302:
http://www.python.org/peps/pep-0302.html
-- What's new on Python 2.3:
http://www.python.org/doc/2.3.4/whatsnew/section-pep302.html
|
by: Maurice LING |
last post by:
Hi,
I think I've hit a system limit in python when I try to construct a list
of 200,000 elements. My error is
malloc: vm_allocate (size = 2400256) failed......
Just wondering is this specific to my system or what? Will adding more
RAM helps in this case?
|
by: Angelos Karantzalis |
last post by:
Hi y'all ...
I'm a bit puzzled here about .NET class instancing under COM+
Issue 1:
I've a COM+ component, let's call it ... COMDbWrapper that initializes
itself from an xml file.
The data in the file change very rarely, so I would like to keep it in a
single copy in-memory if that's possible.
|
by: Kent Lewandowski |
last post by:
hi all,
Recently I wrote some stored procedures using java jdbc code
(admittedly my first stab) and then tried to implement the same within
java packages (for code reuse). I encountered problems doing this.
I wanted to implemented a generic "Helper" class like this:
/**
* Helper
| |
by: sanjeevdivekar |
last post by:
hi,
i am newbie to python so i am trying to learn mod_python as my new
development kit for my small web apps.
i am getting strange result can anybody explain me.
*********************************************************************************************
index.py
*********************************************************************************************
from mod_python import apache
|
by: Zytan |
last post by:
I want multiple instances of the same .exe to run and share the same
data. I know they all can access the same file at the same time, no
problem, but I'd like to have this data in RAM, which they can all
access. It seems like a needless waste of memory to make them all
maintain their own copy of the same data in RAM at the same time.
What's the best way to achieve this?
I've heard of memory mapped files, so maybe that's the answer. ...
|
by: Alex Levinson |
last post by:
Hello -
I am a Perl programmer who's developing a Cocoa application with a development team. Our Cocoa-based application is going to execute some Perl scripts to take care of some systems administration tasks at various times.
I've programmed my Perl script using the DBI:: and DBD::SQLite Perl CPAN packages, but I'm concerned that these packages aren't in a standard Perl installation on OS X 10.6.
What are some of my options to include...
|
by: koduruabhinav |
last post by:
Hi,
I have two files and each consists of modules and in turn modules consists of some verilog
data and instances.i have to search for module name in the two files and comapare the
contents of the modules in the two files.
i have code it does module search,extract the contents of modules and compare
|
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...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
| |
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |