473,758 Members | 2,401 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Better writing in python

I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...

Oct 24 '07 #1
19 1869
On Wed, 24 Oct 2007 12:09:40 +0000, Alexandre Badez wrote:
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
Drop the prefixes. `l` is for list? `d` is for what!? Can't be
dictionary because the code doesn't make much sense.

Where is `cls` coming from?

Ciao,
Marc 'BlackJack' Rintsch
Oct 24 '07 #2
On Oct 24, 1:09 pm, Alexandre Badez <alexandre.ba.. .@gmail.comwrot e:
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
import operator
return filter(cls.dArg uments), filter(operator .not_, cls.dArguments)

Or just:

mandatory = [arg for arg in cls.dArguments in arg]
optional = [arg for arg in cls.dArguments in not arg]
return mandatory, optional

--
Paul Hankin

Oct 24 '07 #3
On Oct 24, 1:09 pm, Alexandre Badez <alexandre.ba.. .@gmail.comwrot e:
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
import operator
return filter(cls.dArg uments), filter(operator .not_, cls.dArguments)

Or just:

mandatory = [arg for arg in cls.dArguments in arg]
optional = [arg for arg in cls.dArguments in not arg]
return mandatory, optional

--
Paul Hankin

Oct 24 '07 #4
On Oct 24, 1:09 pm, Alexandre Badez <alexandre.ba.. .@gmail.comwrot e:
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
import operator
return filter(cls.dArg uments), filter(operator .not_, cls.dArguments)

Or just:

mandatory = [arg for arg in cls.dArguments in arg]
optional = [arg for arg in cls.dArguments in not arg]
return mandatory, optional

--
Paul Hankin

Oct 24 '07 #5
On Oct 24, 7:09 am, Alexandre Badez <alexandre.ba.. .@gmail.comwrot e:
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
You might look into list comprehensions. You could probably do this
with two of them:

<code>
# completely untested
lMandatory = [arg for arg in cls.dArguments if arg is True]
lOptional = [arg for arg in cls.dArguments if arg is False]
</code>

Something like that. I'm not the best with list comprehensions, so I
may have the syntax just slightly off. See the following links for
more information:

http://www.secnetix.de/olli/Python/l...ehensions.hawk
http://docs.python.org/tut/node7.html

Mike

Oct 24 '07 #6
On 2007-10-24, Alexandre Badez <al************ *@gmail.comwrot e:
I'm just wondering, if I could write a in a "better" way this
code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
I don't think there's much improvement to be made. What are your
particular concerns? Is it too slow? Too verbose? Does it not
work correctly?

It appears to be an application of itertools.group by, but that'll
almost certainly be less efficient. To use groupby, you have to
sort by your predicate, and build lists to save results. Your for
loop avoids the sorting.

Here's some instrumentality for ya:

from itertools import groupby
from operator import truth
from collections import defaultdict

result = defaultdict(lis t)
for k, g in groupby(sorted( cls.dArguments, key=truth), truth):
result[k].extend(g)

I like your initial attempt better.

P.S. I didn't realize until working out this example that extend
could consume an iterator.

--
Neil Cerutti
The word "genius" isn't applicable in football. A genius is a guy like Norman
Einstein. --Joe Theisman
Oct 24 '07 #7
Hi Alexandre,

On Oct 24, 2:09 pm, Alexandre Badez <alexandre.ba.. .@gmail.comwrot e:
I'm just wondering, if I could write a in a "better" way this code
Please tell us, what it is you want to achieve. And give us some
context
for this function.
lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)
This snippet will seperate d.Arguments into two lists: one that
holds all elements that are references to True(!) and another list
that holds the rest. The condition 'if args is True' will only
be hold if arg actually _is_ the object _True_. This is probably
not what you want. Apart from that, you might go with

lMandatory = [ arg for arg in cls.dArguments if condition() ]
lOptional = [ arg for arg in cls.dArguments if not condition() ]

the second line could be rewritten

lOptional = list(set(cls.dA rguments)-set(lMandatory) )

If lMandatory and lOptional do not need to be lists, you can also
write

lMandatory = set(arg for arg in cls.dArguments if condition())
lOptional = set(cls.dArgume nts) - lMandatory

But please, give us some more context of what you want to do.

- harold -

Oct 24 '07 #8
Thanks for your try Cliff, I was very confused :P
More over I made some mistake when I post (to make it easiest).

Here is my real code:

with
dArguments = {
'argName' : {
'mandatory' : bool, # True or False
[...], # other field we do not care here
}
}

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if cls.dArguments[arg]['mandatory']:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

So, as you see, we agree each other about "if bool" or "if bool is
True" ;)

So, my question was how to give it a better 'python like' look ?
Any idea ?

Oct 24 '07 #9
Alexandre Badez <al************ *@gmail.comwrot e:
Thanks for your try Cliff, I was very confused :P
More over I made some mistake when I post (to make it easiest).

Here is my real code:

with
dArguments = {
'argName' : {
'mandatory' : bool, # True or False
[...], # other field we do not care here
}
}

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if cls.dArguments[arg]['mandatory']:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

So, as you see, we agree each other about "if bool" or "if bool is
True" ;)

So, my question was how to give it a better 'python like' look ?
Any idea ?

For a 'python like' look lose the Hungarian notation (even Microsoft
have largely stopped using it), increase the indentation to 4 spaces,
and also get rid of the spurious parentheses around the result.
Otherwise it is fine: clear and to the point.

If you really wanted you could write something like:

m, o = [], []
for arg in cls.dArguments:
(m if cls.dArguments[arg]['mandatory'] else o).append(arg)
return m, o

Or even:
m, o = [], []
action = [o.append, m.append]
for arg in cls.dArguments:
action[bool(cls.dArgum ents[arg]['mandatory'])](arg)
return m, o

but it just makes the code less clear, so why bother?
Oct 24 '07 #10

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

Similar topics

6
2142
by: Bengt Richter | last post by:
>>> hex(-5) __main__:1: FutureWarning: hex()/oct() of negative int will return a signed string in Python 2.4 and up '0xfffffffb' >>> hex(-5) '0xfffffffb' >>> hex(-5L) '-0x5L' That is sooo ugly. I suppose it is for a backwards compatible repr, but couldn't we
220
19142
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have any preconceived ideas about it. I have noticed, however, that every programmer I talk to who's aware of Python is also talking about Ruby. So it seems that Ruby has the potential to compete with and displace Python. I'm curious on what basis it...
6
1672
by: Michael | last post by:
Hi, I'm fairly new at Python, and have the following code that works but isn't very concise, is there a better way of writing it?? It seems much more lengthy than python code i have read..... :-) (takes a C++ block and extracts the namespaces from it) def ExtractNamespaces(data): print("Extracting Namespaces")
2
3791
by: Bryan Olson | last post by:
The current Python standard library provides two cryptographic hash functions: MD5 and SHA-1 . The authors of MD5 originally stated: It is conjectured that it is computationally infeasible to produce two messages having the same message digest. That conjecture is false, as demonstrated by Wang, Feng, Lai and Yu in 2004 . Just recently, Wang, Yu, and Lin showed a short- cut solution for finding collisions in SHA-1 . Their result
6
1455
by: Dan Jacobson | last post by:
Can I feel even better about using perl vs. python, as apparently python's dependence of formatting, indentation, etc. vs. perl's "(){};" etc. makes writing python programs perhaps very device dependent. Whereas perl can be written on a tiny tiny screen, and can withstand all kinds of users with various disabilities, etc.? Also perl is easier to squeeze into makefiles.
6
1453
by: Anton Vredegoor | last post by:
Since a few days I've been experimenting with a construct that enables me to send the sourcecode of the web page I'm reading through a Python script and then into a new tab in Mozilla. The new tab is automatically opened so the process feels very natural, although there's a lot of reading, filtering and writing behind the scene. I want to do three things with this post: A) Explain the process so that people can try it for themselves...
7
1803
by: apollonius2 | last post by:
Greetings, I have been working on a little project today to help me better understand classes in Python (I really like Python). I am a self taught programmer and consider myself to fall in the "beginner" category for sure. It was initially sparked by reading about "state machines". This was my attempt at it however I feel it is not quite where it should be: ON = "ON"
3
1536
by: koutoo | last post by:
I have a code that writes to 2 seperate files. I keep getting a "list index out of range" error. The strange part is that when checking the files that I'm writing too, the script has already iterated through and finished writing, yet the error stated implies that it hasn't? So how can it be, that my script has written to the files, yet the error is stating that it hasn't made it through the script? I'll have 15 files that I have...
13
1175
by: Marco Bizzarri | last post by:
Sorry... pressed enter but really didn't want to. As I said, let's say I have a class class A: def __init__(self): self.x = None
0
9492
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
10076
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...
1
9885
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
8744
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
7287
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
5175
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...
1
3832
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
3
3402
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2702
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.