473,761 Members | 5,163 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

if instance exists problem ..

hello,

I've written a convenience wrapper around ConfigObj (which is a imporved
ConfigParser).

Now if I use an instance of the base class, I can easily test is the
instance exists by " if ini:",
like in this example

ini = None
if ini:
print 'ok',type(ini)
else:
print 'wrong',type(in i)
ini = ConfigObj (filename)
if ini:
print 'ok',type(ini)
else:
print 'wrong',type(in i)

Now if I derive a new class form this:
class inifile (ConfigObj):
def __init__ (self, filename):
self.ini = ConfigObj ( filename , list_values = False,
write_empty_val ues = True )
self.ini.newlin es = '\r\n' # not strictly necessary
self.Section = ''
self.Modified = False
the test if an instance exists, always returns false.
ini = inifile (filename)
if ini:
print 'ok',type(ini)
else:
print 'wrong',type(in i)

Why is that ?
What should I do to the same simple test for existance ?

thanks,
Stef Mientki

Oct 17 '07 #1
8 3633
On Oct 17, 11:39 pm, stef mientki <stef.mien...@g mail.comwrote:
the test if an instance exists, always returns false.
ini = inifile (filename)
if ini:
print 'ok',type(ini)
else:
print 'wrong',type(in i)

Why is that ?
What should I do to the same simple test for existance ?
First, object construction always gives you an object or raises an
exception, so you don't have to test for existence. If you don't know
if an object has been created, you should initialise ini to None, and
test with 'if ini is not None:'.

'if x' doesn't test if x exists, it tests if x when cast to a bool is
True. ConfigParser acts like a container, and returns False if it's
empty. Your class is (indirectly) a subclass of ConfigParser, but is
never initialised as such, and so is empty. So 'if ini' returns False,
and you get your confused result.

You need to decide if inifile is a subclass of ConfigObj, or is a
wrapper round a ConfigObj. Probably you want the former and your init
method should be something like:
def __init__(self, filename):
ConfigObj.__ini t__(self, filename, list_values=Fal se,
write_empty_val ues=True)
self.newlines = '\r\n'
self.Section = ''
self.Modified = False

--
Paul Hankin

Oct 17 '07 #2
stef mientki schrieb:
hello,

I've written a convenience wrapper around ConfigObj (which is a imporved
ConfigParser).

Now if I use an instance of the base class, I can easily test is the
instance exists by " if ini:",
like in this example

ini = None
if ini:
print 'ok',type(ini)
else:
print 'wrong',type(in i)
ini = ConfigObj (filename)
if ini:
print 'ok',type(ini)
else:
print 'wrong',type(in i)

Now if I derive a new class form this:
class inifile (ConfigObj):
def __init__ (self, filename):
self.ini = ConfigObj ( filename , list_values = False,
write_empty_val ues = True )
self.ini.newlin es = '\r\n' # not strictly necessary
self.Section = ''
self.Modified = False
the test if an instance exists, always returns false.
ini = inifile (filename)
if ini:
print 'ok',type(ini)
else:
print 'wrong',type(in i)

Why is that ?
What should I do to the same simple test for existance ?
Use isinstance(obj, type).

Diez
Oct 17 '07 #3
"Diez B. Roggisch" <de***@nospam.w eb.dewrites:
stef mientki schrieb:
What should I do to the same simple test for existance ?

Use isinstance(obj, type).
No, that's *far* more specific than "does it exist", and will give
false negatives.

Much better is::

foo = None
foo = do_something_to _get_instance()
# ...
if foo is not None:
# foo was bound to an instance correctly

Even better is just to use the object, and if it's not what was
expected, catch the exception at a level that knows what to do about
it.

--
\ "At my lemonade stand I used to give the first glass away free |
`\ and charge five dollars for the second glass. The refill |
_o__) contained the antidote." -- Emo Philips |
Ben Finney
Oct 17 '07 #4
On Wed, 17 Oct 2007 23:12:15 +0000, Paul Hankin wrote:
'if x' doesn't test if x exists, it tests if x when cast to a bool is
True.
To be pedantic:

Python doesn't have type casts. bool(x) doesn't cast x as a bool, it
creates a brand new Boolean object from x.

Also, the "if x" test looks at x.__nonzero__() first, and if that method
doesn't exist, it looks to see if x.__len__() returns 0 or not. See

http://docs.python.org/ref/customization.html
--
Steven.
Oct 18 '07 #5
On Thu, 18 Oct 2007 03:00:56 +0000, Steven D'Aprano wrote:
On Wed, 17 Oct 2007 23:12:15 +0000, Paul Hankin wrote:
>'if x' doesn't test if x exists, it tests if x when cast to a bool is
True.

To be pedantic:

Python doesn't have type casts. bool(x) doesn't cast x as a bool, it
creates a brand new Boolean object from x.
Actually, to be even more pedantic, True and False are both singletons,
and so bool() doesn't actually create a new Boolean object but reuses the
existing ones.
--
Steven.
Oct 18 '07 #6
En Thu, 18 Oct 2007 00:07:34 -0300, Steven D'Aprano
<st***@REMOVE-THIS-cybersource.com .auescribió:
On Thu, 18 Oct 2007 03:00:56 +0000, Steven D'Aprano wrote:
>On Wed, 17 Oct 2007 23:12:15 +0000, Paul Hankin wrote:
>>'if x' doesn't test if x exists, it tests if x when cast to a bool is
True.

To be pedantic:

Python doesn't have type casts. bool(x) doesn't cast x as a bool, it
creates a brand new Boolean object from x.

Actually, to be even more pedantic, True and False are both singletons,
and so bool() doesn't actually create a new Boolean object but reuses the
existing ones.
To be even more pedantic, 'if x' does not invoke the builtin bool(),
instead it uses PyObject_IsTrue , which returns a plain C integer, not a
Python bool object.

--
Gabriel Genellina

Oct 18 '07 #7
Ben Finney wrote:
"Diez B. Roggisch" <de***@nospam.w eb.dewrites:
>stef mientki schrieb:
What should I do to the same simple test for existance ?

Use isinstance(obj, type).

No, that's *far* more specific than "does it exist", and will give
false negatives.
I've misread the post entirely, so just... discard my message :)

Diez
Oct 18 '07 #8
On Oct 17, 8:00 pm, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com .auwrote:
On Wed, 17 Oct 2007 23:12:15 +0000, Paul Hankin wrote:
'if x' doesn't test if x exists, it tests if x when cast to a bool is
True.

To be pedantic:

Python doesn't have type casts. bool(x) doesn't cast x as a bool, it
creates a brand new Boolean object from x.

Also, the "if x" test looks at x.__nonzero__() first, and if that method
doesn't exist, it looks to see if x.__len__() returns 0 or not. See

http://docs.python.org/ref/customization.html
To be lazy, you can get away with 'if x:' if you *know* that neither
the class nor its superclasses override .__nonzero__ or .__len__,
because the instance then defaults to true. Classes that *do*
override these methods are generally emulating a numeric or collection
type, or are using False to signal "something isn't there".
ConfigParser is doing the latter. That may or may not have been a
good choice by the ConfigParser developers, because it's debatable how
useful it is for empty ConfigParsers to be False. But the fact
remains that it is this way, and an instance of *any* third-party
class may be false for reasons you don't expect.

--Mike

Oct 22 '07 #9

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

Similar topics

34
4764
by: SeeBelow | last post by:
I see the value of a class when two or more instances will be created, but Python programmers regularly use a class when there will only be one instance. What is the benefit of this? It has a disadvantage of a whole lot of "self." being required everywhere, making the code less readable. Also, since a strength of Python is rapid application development, it slows one down to have to put in all those self.'s. The code seems much cleaner...
4
2891
by: Ali | last post by:
Hi, I have a script which I double-click to run. If i double-click it again, it will launch another instance of the script. Is there a way to allow only one instance of a script, so that if another instance of the script is launched, it will just return with an error. Thanks
3
1571
by: Suzanne Vogel | last post by:
** Is there a way (C++ syntax) to specify that a pointer should refer to an object that derives from *two* specific classes? eg, Suppose I have two classes, 'A' and 'B', and I want to specify that pointer 'p' refers to an object derived from both. I *don't* want to invent some class 'Bar' that derives from 'A' and 'B', and specify that pointer 'p' should derive from that class 'Bar'. class A { ...
7
597
by: kon george | last post by:
Can somebody assist. I build this code on a dev laptop and copied across the entire code to a Windows 2003 server with 1.1 framework. It is basic ASP.NE T that uses web service for SQL Server 2000 DB access. The code works fine on my dev laptop, just not on the non dev machine. Here is the full error page:
8
3372
by: mytfein | last post by:
Hi Everyone, Background: Another department intends to ftp a .txt file from the mainframe, for me to process. The objective is to write a vb script that would be scheduled to run daily to process this .txt file. Goal: I am working on a vba script to:
2
1258
by: twick10 | last post by:
I know this is probably a very basic question. Can someone tell me the syntax to check to see if an instance of an object exists? I want to: If (does this instance exist) Then ....... ....... End If
16
2704
by: alexia.bee | last post by:
Hi all, In some weird reason, excel instance won;t die if i remove the comment from 4 lines of setting values into struct. here is a snipcode public System.Collections.Generic.List<frmMain.sDBTest> LoadTestSet(string TestSetFile, System.Collections.Generic.List<frmMain.sDBTestDBviewList)
2
5503
by: Mesan | last post by:
Hello everyone, Thanks to many useful posts in this newsgroup and others, I've been able to come very close to something I've been wanting to do for a very long time. I've figured out how to create a new custom protocol handler in Windows to handle locations like "myProtocol:", which lets me have a shortcut pointing to "myProtocol:myPrimaryKey" and have my application automatically open and display the given account. That's great. I
1
2328
by: Jim Langston | last post by:
Windows. Situation: Using a Python program called OpenRPG. I have a program that displays form data (a character sheet) in C++. I am able in the C++ program to build a string and copy it into the clipboard, then paste it into the input in the running Python program. I would like to somehow automate this, that is, have the python instance communicate with the C++ instance and vice versa. I'm still trying to think of a way to do this. ...
0
9336
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,...
1
9902
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,...
0
9765
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
8770
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...
1
7327
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6603
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
5364
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3446
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2738
bsmnconsultancy
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...

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.