473,782 Members | 2,458 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Favorite non-python language trick?

As someone who learned C first, when I came to Python everytime I read
about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(),
getattr/setattr, the % operator, all of this was very different from C.

I'm curious -- what is everyone's favorite trick from a non-python
language? And -- why isn't it in Python?

Here's my current candidate:

So the other day I was looking at the language Lua. In Lua, you make a
line a comment with two dashes:

-- hey, this is a comment.

And you can do block comments with --[[ and ---]].

--[[
hey
this
is
a
big
comment
--]]

This syntax lets you do a nifty trick, where you can add or subtract a
third dash to change whether or not code runs:

--This code won't run because it's in a comment block
--[[
print(10)
--]]

--This code will, because the first two dashes make the rest a comment,
breaking the block
---[[
print(10)
--]]

So you can change whether or not code is commented out just by adding a
dash. This is much nicer than in C or Python having to get rid of """ or
/* and */. Of course, the IDE can compensate. But it's still neat :)
Jul 19 '05
134 6133
On Sun, 26 Jun 2005 04:08:31 +1000, Steven D'Aprano <st***@REMOVETH IScyber.com.au> wrote:
On Fri, 24 Jun 2005 15:47:45 -0700, James Stroud wrote:
On Friday 24 June 2005 05:58 am, Steven D'Aprano wrote:
with colour do begin
red := 0; blue := 255; green := 0;
end;

instead of:

colour.red := 0; colour.blue := 255; colour.green := 0;

Okay, so maybe it is more of a feature than a trick, but I miss it and it
would be nice to have in Python. How do you like the following? color = type('',(),{})( ) # an instance that will accept attributes
vars(color) {}

The single line replacing
"""
with colour do begin
red := 0; blue := 255; green := 0;
end;
"""
follows: vars(color).upd ate(red=0, blue=255, green=0)
which sets all the attributes: vars(color) {'blue': 255, 'green': 0, 'red': 0} color.blue 255 color.red 0 color.green 0

Of course, I defined a class on the fly above, so I could have given it defaults
as class variables (using English spelling ;-) :
colour = type('Colour',( ),dict(red=0,bl ue=255,green=0) )() # an instance with defaults
vars(colour) {}
Which don't show up in the instance dict, but do show up as attributes: colour.red 0 colour.green 0 colour.blue 255

Then we can update the instance dict that holds its attributes: vars(colour).up date(red=111,gr een=222,blue=33 3)
And they show up, shadowing the class vars vars(colour) {'blue': 333, 'green': 222, 'red': 111}

You can do one attribute this way: vars(colour).up date(red='RED')
vars(colour) {'blue': 333, 'green': 222, 'red': 'RED'}

though this is obviously more concise: colour.green = 'GREEN'
vars(colour) {'blue': 333, 'green': 'GREEN', 'red': 'RED'}
The class vars are still there, even though we don't have a local name binding for the class:
map(vars(type(c olour)).__getit em__, 'red green blue'.split()) [0, 0, 255]

The instance is separate: vars(colour) {'blue': 333, 'green': 'GREEN', 'red': 'RED'}

We can clear those attributes from the instance dict: vars(colour).cl ear()
vars(colour) {}

And then they don't shadow the class vars, so getting attributes make the class vars show again: [getattr(colour, c) for c in 'red green blue'.split()] [0, 0, 255]

Or: map(colour.__ge tattribute__, 'red green blue'.split()) [0, 0, 255]

Actually, you could make that a few characters shorter using a temporary short name to make
a kind of with inside a list comprehension: [[c.red, c.green, c.blue] for c in [colour]][0] [0, 0, 255]

Though list comprehensions leak bindings: c <__main__.Colou r object at 0x02F8FFCC>

Which generator expressions don't: del c
list(([c.red, c.green, c.blue] for c in [colour]))[0] [0, 0, 255] c Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'c' is not defined
Or we can get the pairs and build a dict: [(c,getattr(colo ur, c)) for c in 'red green blue'.split()] [('red', 0), ('green', 0), ('blue', 255)] dict([(c,getattr(colo ur, c)) for c in 'red green blue'.split()]) {'blue': 255, 'green': 0, 'red': 0}

Of course, rgb is usually ordered, so why not
colour = type('Colour',( ),dict(rgb=(0,2 55,0)))() # an instance with default rgb
vars(colour) {} colour.rgb (0, 255, 0) colour.rgb = 111,222,333
vars(colour) {'rgb': (111, 222, 333)} colour.rgb (111, 222, 333) type(colour).rg b
(0, 255, 0)


class color: # americanized
red = 0
blue = 255
green = 0


The problem is, you have made colour (returning to English spelling
instead of foreign) into a class. If you need two colour variables, you
have to duplicate the code for the class (perhaps only changing the
numeric constants. You can't even make instances from the class, because
they all share the same RGB values, which is pretty useless if they are
meant to represent different colours.

Less typing than pascal.


You have missed the point. I'm not comparing Python vs Pascal for
creating records representing RBG values. I'm talking about a Pascal
feature that reduced typing by allowing you to use an implicit record.
Here is one possible way you might use such a feature as a Python idiom,
letting "with" specify an implicit object. Instead of doing this:

# read a class attribute
print myobject.__clas s__.myattribute
# set an instance attribute
myobject.widge t.datapoints[myobject.collec tor] \
= myobject.dispat cher(myobject.w idget.current_v alue)

you might do this:

with myobject:
# read a class attribute
print .__class__.myat tribute
# set an instance attribute
.widget.datapoi nts[.collector] = .dispatcher(.wi dget.current_va lue)


def mywith(o=myobje ct):
# read a class attribute
print o.__class__.mya ttribute
# set an instance attribute
o.widget.datapo ints[o.collector] = o.dispatcher(o. widget.current_ value)
mywith()

Or if we had a lambda-replacing anonymous def permitting full suites:
(def(o=myobject ):
# read a class attribute
print o.__class__.mya ttribute
# set an instance attribute
o.widget.datapo ints[o.collector] = o.dispatcher(o. widget.current_ value)
)()

Is a one-character prefix to the dot objectionable?
Also avoids those stupid little colons.


Using := and = for assignment and equality is precisely as stupid as using
= and == for assignment and equality. Perhaps less stupid: why do we use
== for equals, but not ++ for plus and -- for minus?

I agree, but I think := would be nice in python for RE-binding an existing
binding, wherever it is seen from the local context. Thus you could
write

def foo(): x:=123

and
x = 456
def bar():
x = 789
foo() # finds and rebinds local x
print x
bar() # -> 123
print x # -> 456
foo() # finds and rebinds the global x
print x # -> 123

but
del x
foo() #-> NameError exception, can't find any x to rebind

hm, wandered a bit OT there, ;-/

Regards,
Bengt Richter
Jul 19 '05 #61
On Sat, 25 Jun 2005 19:23:18 +0000, Mandus wrote:
Sat, 25 Jun 2005 16:06:57 GMT skrev Lee Harr:
Higher-order functions like map, filter and reduce. As of Python 3000,
they're non-python tricks. Sigh - i guess it's time for me to get to know
list comprehensions a bit better.

Couldnt there just be a "functional " module ?...

from functional import map, filter, reduce


but lambda is grammar, so probably not so easy to import?

"from __future__ import something" can change the compile-time behaviour
of Python, so it is possible.
--
Steven.

Jul 19 '05 #62

"Mandus" <ma****@gmail.c om> wrote in message
news:sl******** ***********@kas us.simula.no...
Fri, 24 Jun 2005 16:31:08 +0100 skrev Tom Anderson:
On Fri, 24 Jun 2005, Joseph Garvin wrote:
Higher-order functions like map, filter and reduce. As of Python 3000,
they're non-python tricks. Sigh - i guess it's time for me to get to
know
list comprehensions a bit better.


u-huu... I wasn't aware of that. It is really a consensus on this; that
removing map, filter, reduce is a good thing? It will render a whole lot
of my software unusable :(


In his State of Python 2005 address, Guido estimated 1/2 +1, 1/4 +/-0,
1/4 -1 on this. So majority of those with opinion, not 'consensus'. Then
there is his vote...

Terry J. Reedy

Jul 19 '05 #63
On Sat, 25 Jun 2005 15:44:14 -0400, Nicolas Fleury wrote:
Steven D'Aprano wrote:
One of the things I liked in Pascal was the "with" keyword. You could
write something like this:

with colour do begin
red := 0; blue := 255; green := 0;
end;

instead of:

colour.red := 0; colour.blue := 255; colour.green := 0;

Okay, so maybe it is more of a feature than a trick, but I miss it and it
would be nice to have in Python.

With PEP343 (I guess in Python 2.5), you will be able to do something like:
with renamed(colour) as c:
c.red = 0; c.blue = 255; c.green = 0

I think however it is bad. Better solutions to me would be:

colour.setRgb(0 , 255, 0)


But that is no help, because the setRgb method will be implemented as

def setRgb(r, g, b):
self.red = r; self.green = g; self.blue = b

which is exactly the usage case for a with statement:

def setRgb(r, g, b):
with self:
.red = r; .green = g; .blue = b
or

c = myVeryLongNameC olour
c.red = 0; c.blue = 255; c.green = 0


Namespace pollution. It might not matter if c is a temporary variable
inside a function or method, but it does matter if your top-level code is
full of such constructs. Or for that matter, your interactive Python
session.
--
Steven.

Jul 19 '05 #64
On Sat, 25 Jun 2005 21:30:26 +0200, Peter Otten wrote:
Mandus wrote:
By using the builtin reduce, I
move the for-loop into the c-code which performs better.


No. There is no hope of ever writing fast code when you do not actually
measure its performance.

Good grief! You've been spying on Mandus! How else could you possibly know
that he doesn't measure performance? Are you running a key-logger on his
machine? *wink*

For the record, perhaps now is a good time to mention that even Guido
recommended the use of map, filter and reduce in some circumstances:

"Try to use map(), filter() or reduce() to replace an explicit for loop,
but only if you can use a built-in function: map with a built-in function
beats for loop, but a for loop with in-line code beats map with a lambda
function!"

http://www.python.org/doc/essays/list2str.html

He specifically mentions that the reason map will often beat a for loop is
that it moves the work out of Python into the underlying C code.

That is also one of the reasons that ''.join(L) is faster than

s = ''
for item in L:
s = s + item

Do we really need to profile our code every single time to know this?
Isn't it reasonable to just say, "I use join because it is faster than
adding strings" without being abused for invalid optimization?

--
Steven.

Jul 19 '05 #65


On Saturday 25 June 2005 11:08 am, Steven D'Aprano wrote:
The problem is, you have made colour (returning to English spelling
instead of foreign) into a class. If you need two colour variables, you
have to duplicate the code for the class (perhaps only changing the
numeric constants. You can't even make instances from the class, because
they all share the same RGB values, which is pretty useless if they are
meant to represent different colours.


py> class color:
.... pass
....
py> def with(classname, **kwargs):
.... classname.__dic t__.update(kwar gs)
....
py> with(color, red=0,
.... blue=255,
.... green=255)
py>
py> color.blue
255

Is this what you want to do?
Also avoids those stupid little colons.


Using := and = for assignment and equality is precisely as stupid as using
= and == for assignment and equality. Perhaps less stupid: why do we use
== for equals, but not ++ for plus and -- for minus?


The colons are to make it look more official or something. They are useless
and hence stupid. The two equals signs for comparison could be argued to be
redundant, but the colons are absolutely unecessary. I thought they were
pointless 18 years ago when I learned pascal in highschool and after 20
years, I still think they are still pointless.

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 19 '05 #66
On Sat, 25 Jun 2005 13:31:19 -0700, Robert Kern wrote:
Of course, in a Python 3000 world, nothing stops anyone from using their
own extension module implementing map, filter, and reduce if they really
want to. TSBOOOWTDI in the language/stdlib, but it shouldn't stop anyone
from using other ways to do it that aren't in the stdlib if the
tradeoffs are right for them.


Now that's a good point. Since Guido has said that one of the major
motivations for removing the functional programming tools like map, filter
and reduce is that There Should Be Only One Obvious Way To Do It, and
Guido also seems to really like list comprehensions, is it fair to
assume that for-loops will be removed from Python 3000 too?

Or are they safe until Python 4000?

*wink*

Of course, I also know that Guido has said a foolish consistency
is the hobgoblin of little minds, and I would never accuse him of being a
little mind. But one of the things I like about Python is that it has
found a nice balance between There Is Always Another Way, and The Language
Is A Straight Jacket.

It is blindingly easy to refactor map and filter as in-line list comps,
and Guido's comments suggest to me that they are safe until list comps are
significantly faster. But reduce needs to be re-factored as a for loop,
with all the disadvantages that implies. I think that if people like
Mandus have good real-world usage cases for reduce, it can be saved, at
least as part of itertools.
--
Steven.

Jul 19 '05 #67
On Sat, 25 Jun 2005 23:19:48 +0200, Peter Otten wrote:
Python is more about readability than raw speed, and I prefer a for-loop
over reduce() in that respect, too.


Fascinating. I prefer reduce for readability. "Reduce this list to one
value, using this known behaviour" seems to work for me better than:

"Oh look, here is a new name being defined. What is it for I wonder? Now
it is being used in a for loop. Ah, the loop appears to be implementing
the well-known reduce behaviour from Lisp. I bet that means that the name
is a temporary placeholder just being used to hold the intermediate
results of from the for loop. Yes, that seems to be the case."

Funny how people differ in what they find readable :-)
--
Steven.

Jul 19 '05 #68
On Saturday 25 June 2005 06:44 pm, James Stroud wrote:
I thought they were
pointless 18 years ago when I learned pascal in highschool and after 20
years, I still think they are still pointless.


I think that fails "==".

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 19 '05 #69
On Sat, 25 Jun 2005 18:44:12 -0700, James Stroud wrote:
On Saturday 25 June 2005 11:08 am, Steven D'Aprano wrote:
The problem is, you have made colour (returning to English spelling
instead of foreign) into a class. If you need two colour variables, you
have to duplicate the code for the class (perhaps only changing the
numeric constants. You can't even make instances from the class, because
they all share the same RGB values, which is pretty useless if they are
meant to represent different colours.
py> class color:
... pass
...
py> def with(classname, **kwargs):
... classname.__dic t__.update(kwar gs)
...
py> with(color, red=0,
... blue=255,
... green=255)
py>
py> color.blue
255

Is this what you want to do?


No it isn't. That doesn't help at all if you want to do something
other than assigning to instance attributes.

For starters, it doesn't help me do this:

with colour:
print "Blue =", .blue
print "Green =", .green
print "Red =", .red

or anything more complex:

with my_directory_ob ject:
L = .raw_paths
L.append("~/custom/")
# move the last directory looked to the front
# and the current directory to the end
.normalise(L, first=.last_dir , last=".")
.paths = L
try:
.currentpos += 1
except AttributeError:
.currentpos = 0

The point is that a hypothetical "with" block would have to allow
arbitrary access to dotted names: getting, setting, deletion, and method
calling, not just one very limited form of keyword assignment.
> Also avoids those stupid little colons.


Using := and = for assignment and equality is precisely as stupid as using
= and == for assignment and equality. Perhaps less stupid: why do we use
== for equals, but not ++ for plus and -- for minus?


The colons are to make it look more official or something.


That is the most ridiculous thing I have ever heard about a programming
language.

Has it escaped your notice that every language has to distinguish in
some way between "x equals 1" in the sense of assignment and "x equals 1"
in the sense of comparisons? "x = 1" is ambiguous.

A language might use constructs like:

"SET x = 1" and "x = 1"

for assignment and comparison, or do what Python does:

"x = 1" and "x == 1"

or do what Pascal does:

"x := 1" and "x = 1"

Even if the compiler can always unfailing tell them apart from context,
for the sake of the human programmers who have to read and write the code,
it is important to have two different operators.

They are useless and hence stupid.
Useless huh? Just try leaving them out and see how useless they are.
The two equals signs for comparison could be argued to be
redundant,
No they aren't redundant, because assignment and equality testing are very
different. And in Python, you can even use them in the same place, so you
can't expect the compiler to tell them apart from context.

py> x = 2 # did I mean assignment or comparison?
but the colons are absolutely unecessary. I thought they were
pointless 18 years ago when I learned pascal in highschool and after 20
years, I still think they are still pointless.


You didn't learn Pascal very well then if you can't see the difference
between assignment and equality testing.
--
Steven.

Jul 19 '05 #70

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

Similar topics

3
2826
by: Randy Given | last post by:
What is your favorite Java development environment? What others have you tried? What are some pros and cons of each? Thanks!
0
3492
by: Vic Cekvenich | last post by:
Here is my favorite tag: http://displaytag.sf.net and see examples (in upper right). Grid, Sorting, nested, group, export, everything you like, plus it's free. Here is example code of how I used it: http://cvs.sourceforge.net/viewcvs.py/basicportal/bPproj/bP/WEB-INF/pgs/forums/ArticleLst.jsp You can view here run time by clicking here: http://basebeans.com/do/channelsPg
2
1454
by: Matthew Louden | last post by:
I want to make a link that allows users to add my web site to the favorite in IE. Anyone knows how to do that?
9
1539
by: Scott McNair | last post by:
What's your favorite bit of "short-cut" code that you use? One of my favorite shortcuts I'll use when coding a page is to create a sub along the lines of the following: Sub Print(myText) Response.Write myText & vbcrlf End Sub And then I use Print instead of Response.Write thru my code.
1
1290
by: edunetgen | last post by:
I have a Web Aplication. I want an own image when an user adds me to favorite. Thanks, Edu
2
1514
by: zhaoyandong | last post by:
One of my interviewers ask me "Two favorite features of C++, and over-rated, and misued features" Could anybody give me some advice on this? Thanks
2
1955
by: Les | last post by:
In ancient times I had a desire to make a game and I started to do so, I quickly found the project was beyond the hardware's capability for that era (even in assembler) and had to shelf the project. I retried in the dark ages of computers, when I was in college, and got much further before realizing the same thing was taking place and shelved the project again. In hopes that this new PC technology may yeild something interesting. ...
3
1036
by: Jensen bredal | last post by:
Hello, I need to offer the visitors of my siste to add it to the favorite list but only when it is ot there. the code below: window.external.AddFavorite(location.href, document.title) add the link. How can i see if the current link is already there?
1
1128
by: clintonG | last post by:
Want to give up your most treasured posession? Post the URL for your favorite RegEx library you've found most useful for validating form input. <%= Clinton Gallagher METROmilwaukee (sm) "A Regional Information Service" NET csgallagher AT metromilwaukee.com URL http://metromilwaukee.com/ URL http://clintongallagher.metromilwaukee.com/
4
2172
by: fiversen | last post by:
Hello, I have a site for the collegue with a football winning game. ...fussball.html there I redirect the user to an cgi-page ../f11.cgi
0
9480
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
10313
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...
0
10146
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...
0
9944
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...
1
7494
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
6735
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
5378
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...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4044
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 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.