473,664 Members | 2,728 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Test for structure

Hi there,

how can I check if a variable is a structure (i.e. a list)? For my
special problem the variable is either a character string OR a list of
character strings line ['word1', 'word2',...]

So how can I test if a variable 'a' is either a single character string
or a list? I tried:

if a is list:
but that does not work. I also looked in the tutorial and used google
to find an answer, but I did not.

Has anyone an idea about that?

Alex

Jul 18 '05 #1
18 1856
import types

v = []
if type(v) is types.ListType:
pass
--
Regards,

Diez B. Roggisch
Jul 18 '05 #2
On Wed, 16 Feb 2005 07:11:08 -0800 (PST), alex
<al************ *@mpi-hd.mpg.de> wrote:
how can I check if a variable is a structure (i.e. a list)? For my
special problem the variable is either a character string OR a list of
character strings line ['word1', 'word2',...]

So how can I test if a variable 'a' is either a single character string
or a list? I tried:

if a is list:

but that does not work. I also looked in the tutorial and used google
to find an answer, but I did not.

Has anyone an idea about that?


<http://www.brunningonl ine.net/simon/blog/archives/001349.html>

--
Cheers,
Simon B,
si***@brunningo nline.net,
http://www.brunningonline.net/simon/blog/
Jul 18 '05 #3
Perhaps you're looking for the type() built in function and the types modules?
type('aaa') <type 'str'> type([]) <type 'list'> import types
if type([]) is types.ListType:
.... print 'is a list'
....
is a list

Chris

On Wed, 16 Feb 2005 07:10:56 -0800 (PST), alex
<al************ *@mpi-hd.mpg.de> wrote: Hi there,

how can I check if a variable is a structure (i.e. a list)? For my
special problem the variable is either a character string OR a list of
character strings line ['word1', 'word2',...]

So how can I test if a variable 'a' is either a single character string
or a list? I tried:

if a is list:

but that does not work. I also looked in the tutorial and used google
to find an answer, but I did not.

Has anyone an idea about that?

Alex

--
http://mail.python.org/mailman/listinfo/python-list

--
"It is our responsibilitie s, not ourselves, that we should take
seriously." -- Peter Ustinov
Jul 18 '05 #4
alex wrote:
So how can I test if a variable 'a' is either a single character string
or a list?


py> def test(x):
.... return (isinstance(x, list) or
.... isinstance(x, basestring) and len(x) == 1)
....
py> test('a')
True
py> test('ab')
False
py> test([])
True
py> test(['a', 'b'])
True

But definitely read Simon Brunning's post - you probably don't actually
want to do this test. Why do you think you want to test this? What's
your use case?

STeVe
Jul 18 '05 #5
I use a function isListLike in cases such as this one:

# def isListLike(L):
# """Return True if L is list-like, False otherwise."""
# try:
# L + []
# return True
# except:
# return False

Then you can use a standard if-else construct:

# if isListLike(myva r):
# <do something>
# else:
# <do something else>

Michael

--
Michael D. Hartl, Ph.D.
Chief Technology Officer
http://quarksports.com/

Jul 18 '05 #6
Michael Hartl wrote:
I use a function isListLike in cases such as this one:

# def isListLike(L):
# """Return True if L is list-like, False otherwise."""
# try:
# L + []
# return True
# except:
# return False

Then you can use a standard if-else construct:

# if isListLike(myva r):
# <do something>
# else:
# <do something else>


What kind of situations do you use this for? I almost never have to do
this kind of typechecking. If it's supposed to be a list, I just use it
as a list...

STeVe
Jul 18 '05 #7
alex wrote On 17/02/05 02:08:
how can I check if a variable is a structure (i.e. a list)? For my
special problem the variable is either a character string OR a list
of character strings line ['word1', 'word2',...]


You're trying to apply the LBYL principle. My bet is that your "special
problem" can be solved by the EAFP principle. (These terms are
explained in the Glossary of the tutorial,
<http://www.python.org/doc/current/tut/node18.html>.)

If you test for a specific set of types, your code will not work with
types that you have not considered yet behave like lists. As you
discover more object types that you want the code to work with, it will
sprout more cruft for checking those types.

If you want to use some list behaviour of the object, don't check first.
Use it, and catch the TypeError exception in the event that it's not.
This way, *any* object that implements the functionality you need will
work, regardless of its type.
Jul 18 '05 #8
On Wednesday 16 February 2005 09:08 am, alex wrote:
how can I check if a variable is a structure (i.e. a list)? For my
special problem the variable is either a character string OR a list of
character strings line ['word1', 'word2',...]

So how can I test if a variable 'a' is either a single character string
or a list?


The literally correct but actually wrong answer is:

if type(a) == type([]):
print "'a' is a duck"

But you probably shouldn't do that. You should probably just test to
see if the object is iterable --- does it have an __iter__ method?

Which might look like this:

if hasattr(a, '__iter__'):
print "'a' quacks like a duck"

That way your function will also work if a happens to be a tuple,
a dictionary, or a user-defined class instance which is happens to
be iterable.

Being "iterable" means that code like:

for i in a:
print "i=%s is an element of a" % repr(i)

works. Which is probably why you wanted to know, right?

Cheers,
Terry

--
--
Terry Hancock ( hancock at anansispacework s.com )
Anansi Spaceworks http://www.anansispaceworks.com

Jul 18 '05 #9
I don't believe you can use the test for a __iter__ attribute in this
case, for the following reason:
c1 = 'abc'
c2 = ['de', 'fgh', 'ijkl']
hasattr(c1, '__iter__') False hasattr(c2, '__iter__') True for i in c1: print "i=%s is an element of c1" % repr(i)
....
i='a' is an element of c1
i='b' is an element of c1
i='c' is an element of c1

In other words, even though the c1 single string variable does not have
an __iter__ attribute, it can still be used in a for loop. I think the
right answer would depend on what exactly the OP intends to do with the
argument when it is a list (or is list-like in some way) -- i.e. he
didn't say specifically that he wanted use it in a for loop.

-Martin
=============== =====
Terry Hancock wrote:
On Wednesday 16 February 2005 09:08 am, alex wrote:
how can I check if a variable is a structure (i.e. a list)? For my
special problem the variable is either a character string OR a list

of character strings line ['word1', 'word2',...]

So how can I test if a variable 'a' is either a single character string or a list?


The literally correct but actually wrong answer is:

if type(a) == type([]):
print "'a' is a duck"

But you probably shouldn't do that. You should probably just test to
see if the object is iterable --- does it have an __iter__ method?

Which might look like this:

if hasattr(a, '__iter__'):
print "'a' quacks like a duck"

That way your function will also work if a happens to be a tuple,
a dictionary, or a user-defined class instance which is happens to
be iterable.

Being "iterable" means that code like:

for i in a:
print "i=%s is an element of a" % repr(i)

works. Which is probably why you wanted to know, right?

Cheers,
Terry

--
--
Terry Hancock ( hancock at anansispacework s.com )
Anansi Spaceworks http://www.anansispaceworks.com


Jul 18 '05 #10

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

Similar topics

7
2155
by: Dave Smithz | last post by:
Hi There, I have taken over someone else's PHP code and am quite new to PHP. I made some changes and have implemented them to a live environment fine so far. However, I now want to setup a test environment. All the PHP scripts start with a few lines of: require_once "library file at specific location on server"
4
3065
by: Edvard Majakari | last post by:
Hi, I just found py.test and converted a large unit test module to py.test format (which is actually almost-no-format-at-all, but I won't get there now). Having 348 test cases in the module and huge test classes, I started to think about splitting classes. Basically you have at least three obvious choises, if you are going for consistency in your test modules: Choise a:
41
10266
by: Roy Smith | last post by:
I've used the standard unittest (pyunit) module on a few projects in the past and have always thought it basicly worked fine but was just a little too complicated for what it did. I'm starting a new project now and I'm thinking of trying py.test (http://codespeak.net/py/current/doc/test.html). It looks pretty cool from the docs. Is there anybody out there who has used both packages and can give a comparative review?
2
2778
by: B. Wood | last post by:
I have written a simple program the has a structure with two members. There are two strange things going on. 1. When on of the structure members is tested in a condition, the value of the second member seems to change. 2. The order of the condition test seems to have an effect on if the one structure member changes.
2
2424
by: Netkiller | last post by:
#!/usr/bin/python # -*- coding: utf-8 -*- """ Project: Network News Transport Protocol Server Program Description: 基于数据库的新闻组,实现BBS前端使用NNTP协议来访问贴子 Reference: NNTP协议: http://www.mibsoftware.com/userkt/0099.htm 正则表达式: http://wiki.woodpecker.org.cn/moin/RegExpInPython#head-2358765384844ed72f01658cbcde24613d941e9d
9
2064
by: Deckarep | last post by:
Hello Group, I actually have two seperate questions regarding Unit Testing with NUnit in C#. Please keep in mind that I'm new to the concept of Unit Testing and just barely coming around to feeling comfortable writing tests first and code after as in TDD style. Question 1: How can you effectively start incorporating Unit Testing in your
0
1191
by: Alan Isaac | last post by:
This is really a repackaging of an earlier question, probably illustrating that I still do not understand relative imports. Suppose I have the package structure (taken from the example at http://www.python.org/dev/peps/pep-0328/) package/ __init__.py subpackage1/ __init__.py
4
1251
by: melissa86 | last post by:
My son needs to take a computer test to take an on-line class. He knows what most everything is except for the following. I have no idea about this myself unless they are just using terms I am not familiar with. I may know how to do it, just don't know the terms. Can someone help? Read and write file paths Recognizing the parent or child in a folder structure ...
2
2600
by: =?Utf-8?B?c2lwcHl1Y29ubg==?= | last post by:
I was wonder if there is any protocol or suggestions on how to setup unit testing projects in large solution??? If you have a large solution of say 50 projects and add a project for every unit test it could get overwhelming - is there some standards on how to set this up??? Has anyone integrated this into Continuous Integration ???
0
8348
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
8778
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...
1
8549
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
8636
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
7375
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 projectplanning, coding, testing, and deploymentwithout 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
5660
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
4351
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2003
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1759
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.