Hello all,
Today I found myself once again defining two functions that I use all
the time: nsplit and iterable. These little helper functions of mine
get used all the time when I work. Im sick of having to define them
(but am very good at it these days, less than 1 typo per function!).
It leads me to the following questions
1. Is this functionality already built in and im just missing it
2. Is there some well known, good technique for these that I missed?
3. Insert question I need to ask here (with a response)
These are the funtions w/ explaination:
def nsplit(s,p,n):
n -= 1
l = s.split(p, n)
if len(l) < n:
l.extend([''] * (n - len(l)))
return l
This is like split() but returns a list of exactly lenght n. This is
very useful when using unpacking, e.g.:
x, y = nsplit('foo,bar ,baz', ',', 2)
def iterable(item, count_str=False ):
if not count_str and isinstance(item , str):
return False
try:
iter(item)
except:
return False
return True
This is just simple boolean test for whether or not an object is
iterable. I would like to see this in builtins, to mirror callable.
The optional count_str adds flexibility for string handling, since
sometimes I need to iterate over a string, but usually not. I
frequently use it to simplify my case handling in this type of
costruct:
def foo(bar):
bar = bar if iterable(bar) else [bar]
for x in bar:
....
Thanks for feeback,
Erich 11 1397
On Apr 15, 1:51 pm, Erich <sophac...@gmai l.comwrote:
Hello all,
Today I found myself once again defining two functions that I use all
the time: nsplit and iterable. These little helper functions of mine
get used all the time when I work. Im sick of having to define them
(but am very good at it these days, less than 1 typo per function!).
It leads me to the following questions
1. Is this functionality already built in and im just missing it
2. Is there some well known, good technique for these that I missed?
3. Insert question I need to ask here (with a response)
These are the funtions w/ explaination:
def nsplit(s,p,n):
n -= 1
l = s.split(p, n)
if len(l) < n:
l.extend([''] * (n - len(l)))
return l
The split() method has a maxsplit parameter that I think does the same
thing. For example:
>>temp = 'foo,bar,baz' temp.split(', ', 1)
['foo', 'bar,baz']
See the docs for more info: http://docs.python.org/lib/string-methods.html
This is like split() but returns a list of exactly lenght n. This is
very useful when using unpacking, e.g.:
x, y = nsplit('foo,bar ,baz', ',', 2)
def iterable(item, count_str=False ):
if not count_str and isinstance(item , str):
return False
try:
iter(item)
except:
return False
return True
This is just simple boolean test for whether or not an object is
iterable. I would like to see this in builtins, to mirror callable.
The optional count_str adds flexibility for string handling, since
sometimes I need to iterate over a string, but usually not. I
frequently use it to simplify my case handling in this type of
costruct:
def foo(bar):
bar = bar if iterable(bar) else [bar]
for x in bar:
....
Thanks for feeback,
Erich
Not sure about the other one, but you might look at itertools.
Mike
On Apr 15, 1:51 pm, Erich <sophac...@gmai l.comwrote:
Hello all,
Today I found myself once again defining two functions that I use all
the time: nsplit and iterable. These little helper functions of mine
get used all the time when I work. Im sick of having to define them
(but am very good at it these days, less than 1 typo per function!).
It leads me to the following questions
1. Is this functionality already built in and im just missing it
2. Is there some well known, good technique for these that I missed?
3. Insert question I need to ask here (with a response)
These are the funtions w/ explaination:
def nsplit(s,p,n):
n -= 1
l = s.split(p, n)
if len(l) < n:
l.extend([''] * (n - len(l)))
return l
This is like split() but returns a list of exactly lenght n. This is
very useful when using unpacking, e.g.:
x, y = nsplit('foo,bar ,baz', ',', 2)
def iterable(item, count_str=False ):
if not count_str and isinstance(item , str):
return False
try:
iter(item)
except:
return False
return True
This is just simple boolean test for whether or not an object is
iterable. I would like to see this in builtins, to mirror callable.
The optional count_str adds flexibility for string handling, since
sometimes I need to iterate over a string, but usually not. I
frequently use it to simplify my case handling in this type of
costruct:
Just found this thread on the subject: http://mail.python.org/pipermail/pyt...ly/394487.html
That might answer your question.
>
def foo(bar):
bar = bar if iterable(bar) else [bar]
for x in bar:
....
Thanks for feeback,
Erich
Mike
Erich schrieb:
This is like split() but returns a list of exactly lenght n. This is
very useful when using unpacking, e.g.:
x, y = nsplit('foo,bar ,baz', ',', 2)
You could use the second argument of split:
x, y = 'foo,bar,baz'.s plit(',', 1)
Note that the number has the meaning "only split n times" as opposed to
"split into n parts".
Cheers,
Robin
Today I found myself once again defining two functions that I use all
the time: nsplit and iterable. These little helper functions of mine
get used all the time when I work. Im sick of having to define them
(but am very good at it these days, less than 1 typo per function!).
It leads me to the following questions
How about creating an erichtools module?
>def nsplit(s,p,n):
> n -= 1 l = s.split(p, n) if len(l) < n: l.extend([''] * (n - len(l))) return l
The split() method has a maxsplit parameter that I think does the same
thing. For example:
>>>temp = 'foo,bar,baz' temp.split(' ,', 1)
['foo', 'bar,baz']
The OP's code *does* use the maxsplit parameter of split()
The important (and missing) aspect of the OP's code in your
example is exercised when there are *fewer* delimited pieces than
"n":
>>"a,b,c".split (',', 5)
['a', 'b', 'c']
>>nsplit("a,b,c ", ',', 5)
['a', 'b', 'c', '', '']
A few things I noticed that might "improve" the code:
- cache len(l) though my understanding is that len() is an O(1)
operation, so it may not make a difference
- using "delim", "maxsplit", "results" instead of "p", "n" "l" to
make it easier to read
-setting default values to match split()
def nsplit(s, delim=None, maxsplit=None):
if maxsplit:
results = s.split(delim, maxsplit)
result_len = len(results)
if result_len < maxsplit:
results.extend([''] * (maxsplit - result_len)
return results
else:
return s.split(delim)
My suggestion would just be to create your own utils.py module
that holds your commonly used tools and re-uses them
-tkc
On Apr 15, 3:15 pm, Tim Chase <python.l...@ti m.thechases.com wrote:
<snip>
>
My suggestion would just be to create your own utils.py module
that holds your commonly used tools and re-uses them
-tkc
Well, I almost said that, but I was trying to find some "battery"
included that he could use since the OP seemed to want one. I'm sure
there's a geeky way to do this with lambdas or list comprehensions
too.
Thanks for the feedback though.
Mike
Tim Chase wrote:
def nsplit(s, delim=None, maxsplit=None):
if maxsplit:
results = s.split(delim, maxsplit)
result_len = len(results)
if result_len < maxsplit:
results.extend([''] * (maxsplit - result_len)
return results
else:
return s.split(delim)
I'll add a couple more suggestions:
1. Delay the test for maxsplit, as str.split() does the right thing if
maxsplit is None.
2. Use a generator to pad the list, to avoid interim list creation. This
works fine, because list.extend() accepts any iterable. This also shortens
the code a bit, because xrange() does the right thing in this case with
negative numbers. For example:
def nsplit(s, delim=None, maxsplit=None):
results = s.split(delim, maxsplit)
if maxsplit is not None:
results.extend( '' for i in xrange(maxsplit - len(results)))
return results
Jeffrey
Erich wrote:
def iterable(item, count_str=False ):
if not count_str and isinstance(item , str):
return False
try:
iter(item)
except:
return False
return True
Beware the "except" clause here, as it catches *all* errors. Thus, if you
happen to have an unfortunate typo:
try:
iter(iten)
except:
return False
return True
then your code will happily return False for everything. This code should
catch TypeErrors only for better results:
try:
iter(item)
except TypeError:
return False
return True
Jeffrey
On Tue, 2008-04-15 at 11:51 -0700, Erich wrote:
Hello all,
Today I found myself once again defining two functions that I use all
the time: nsplit and iterable. These little helper functions of mine
get used all the time when I work. Im sick of having to define them
(but am very good at it these days, less than 1 typo per function!).
It leads me to the following questions
1. Is this functionality already built in and im just missing it
2. Is there some well known, good technique for these that I missed?
3. Insert question I need to ask here (with a response)
These are the funtions w/ explaination:
def nsplit(s,p,n):
n -= 1
l = s.split(p, n)
if len(l) < n:
l.extend([''] * (n - len(l)))
return l
This is like split() but returns a list of exactly lenght n. This is
very useful when using unpacking, e.g.:
x, y = nsplit('foo,bar ,baz', ',', 2)
def iterable(item, count_str=False ):
if not count_str and isinstance(item , str):
return False
try:
iter(item)
except:
return False
return True
This is just simple boolean test for whether or not an object is
iterable. I would like to see this in builtins, to mirror callable.
The optional count_str adds flexibility for string handling, since
sometimes I need to iterate over a string, but usually not. I
frequently use it to simplify my case handling in this type of
costruct:
def foo(bar):
bar = bar if iterable(bar) else [bar]
for x in bar:
....
Thanks for feeback,
Erich
As far as I know there is no built in function that does exactly what
you want. You can certainly simplify your nsplit function a bit, but as
mentioned, it's probably best just to create your own package and keep
your utility functions there.
It's worth noting that you almost certainly want to be doing
isinstance( item, basestring ) in your iterable function instead of
isinstance( item, str ), or things will get very surprising for you as
soon as you have to deal with a unicode string.
If you don't want the hassle of creating a separate package, and you're
only interested in having these functions be handy on your local python
install, you could also add them into your sitecustomize file as
described here: http://docs.python.org/lib/module-site.html
On linux, that's as easy as creating a file
named /usr/lib/python2.5/sitecustomize.p y that inserts whatever you want
into the __builtin__ module, and it'll be automatically imported
whenever you run python.
I'd doubt there's a case for getting this functionality added to the
language, as your use case seems pretty specific, and it's just not that
hard to write the function that does what you want to do.
--
John Krukoff <jk******@ltgc. com>
Land Title Guarantee Company This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Shabam |
last post by:
I'm having a calendar feature developed whereby users can add recurring
events. These recurring events can have start and end dates, meaning they
will recur only within a date range. For instance, user A creates an event
that recurs every Tuesday, from 1/1/05 - 3/2/06.
The developer has decided that it would be good to have another table that
stores each individual recurring event in a separate record. His logic is
that this will help...
|
by: gil |
last post by:
I initially tried building a coded system where numbers 1 through 10
referenced a certain type of recurring appointment, and would then call a
specific function for each, but as more appointments were added things began
to slow down quite a bit. I've taken a different approach since, and decided
to create a single record for each recurring appointment, but this has
problems as well due to the fact that I have to search each time slot going...
|
by: Josh28 |
last post by:
Hi
We are a group of two chaps just out of undergrad, we created
a software to automate the use of Design Patterns. We have put it up
at Source Forge--http://dpatoolkit.sourceforge.net/
The software has been designed using the .NET framework and
coded in C#.
The patterns can be stored as plug-ins in XML, adding any
number of attributes like Intent, Behavior and the like... Class
|
by: steve |
last post by:
Hi All
I am writing a program for a gymnasium for membership control
It is the first time I have had to deal with appointment diaries and I want
to know the best way to store recurring appointments
1. Do I calculate and save all future appointments as table records at the
time of creation of the Recurring appointment or ..
2. Do I just save the details and create the appointments in code whenever
|
by: nepdae |
last post by:
Please forgive me, this is a long one.
My 11-user Access 2000 database is having recurring corruption
problems. The symptoms include the following:
1) corrupted fields in recently created or accessed records
2) incorrectly linked records via primary and foreign keys (looking at
the tables displays the correct key number but when filtered it links
to a different number).
3) truncating of text entered in a memo field
| |
by: JosAH |
last post by:
Greetings,
this week we let go of all that algebraic stuff and concentrate a bit more on
what object oriented programming is all about. Java claims to support OO, so
why not use it? In this week's article we're going to talk a bit about when
and why to apply certain patterns. We'll start with the Visitor pattern.
The pattern is also named 'double dispatch' which will become clear near the
end of this little article. Here's the...
|
by: weaknessforcats |
last post by:
Design Patterns – State
Often computer software operates based on a condition called a state. These states traditionally have been implemented using a switch statement. The cases of the switch represent the various states. The example below might be used to read a disc file
int state = 1;
switch (state)
{
case 1:
//open the file
|
by: weaknessforcats |
last post by:
Design Patterns: Visitor
Introduction
Polymorphism requires a class hierarchy where the interface to the hierarchy is in the base class. Virtual functions allow derived classes to override base class functions. Applications using polymorphism typically have functions with base class pointers or references as arguments. Then derived objects are created and used as arguments to these functions. Inside the function, only the base class methods...
|
by: =?Utf-8?B?TWVlbWEgSnVkeQ==?= |
last post by:
I have a Verizon Palm Treo 755p and use Outlook 2002 on my new HP Pavilion
(Vista 64-bit). When I was syncing on my old XP PC, everything worked fine.
On the Vista PC, when I finally got it to sync (using a Bluetooth USB
adapter), I ended up with recurring appointments that act wierd when I try to
delete, move or edit them. It won't allow any of these changes, saying
various messages:
1) If I try to open the recurring appointment: ...
|
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,...
|
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...
| |
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...
|
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: 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...
|
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: 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: 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...
| | |