473,782 Members | 2,479 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 6132
On Sat, 25 Jun 2005 23:08:10 +0000, Bengt Richter wrote:
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)


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.

I understand how to manipulate __dict__ as an more complicated (dare I say
obfuscated?) way of assigning to object attributes.
[snip]
We can clear those attributes from the instance dict: vars(colour).cl ear()
vars(colour) {}
Which has the unfortunate side effect of also destroying any other
instance attributes.

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()


[snip]
Is a one-character prefix to the dot objectionable?


That's a good workaround, subject to namespace pollution issues, and one
that I'm aware of. Although do you really want to be creating a unique
function definition every time you want to use the with idiom?

I'm not about to stop using Python because of the lack of Pascal-like
"with" blocks. It is a nice feature to have, but I'm aware that Guido
prefers explicit to implicit and "with" is extremely implicit.

--
Steven.

Jul 19 '05 #71
On Sat, 25 Jun 2005 23:08:10 +0000, Bengt Richter wrote:
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, ;-/


Given how much the use of global variables are discouraged, is it a
good idea to allow even more inter-namespace interactions?
--
Steven.

Jul 19 '05 #72
Steven D'Aprano wrote:
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*


His mentioning reduce() as a performance panacea was a strong indication
even without looking over his shoulders. He filled in some conditions in a
later post, but "[u]sing reduce ... performs better [than a for-loop]" is
just wrong.
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:
Personally I wouldn't rely on authority when I can measure without much
hassle. And the lesson I take from Guido's essay is rather how he got to
his conclusions than what his actual findings were. After all, Python may
have advanced a bit since he wrote the text.
Do we really need to profile our code every single time to know this?
No. Only if we care about the performance of a particular piece. And if we
do we are sometimes in for a surprise.
Isn't it reasonable to just say, "I use join because it is faster than
adding strings" without being abused for invalid optimization?


OK, I am making a guess: "".join(strings ) is more often faster than
naive string addition than reduce() wins over a for-loop.

I don't think my pointed comment qualifies as "abuse", by the way.

Peter

Jul 19 '05 #73
On 25 Jun 2005 12:17:20 -0700, George Sakkis <gs*****@rutger s.edu> wrote:
If they go to itertools, they can simply be:

def map(f, *iterables):
return list(imap(f,*it erables))

def filter(f, seq):
return list(ifilter(f, seq))

from itertools import ifilter
def filter(f, seq): .... return list(ifilter(f, seq)) filter(str.isal pha, 'not quite!') ['n', 'o', 't', 'q', 'u', 'i', 't', 'e'] __builtins__.fi lter(str.isalph a, 'not quite!')

'notquite'

- kv
Jul 19 '05 #74
On Saturday 25 June 2005 01:08 pm, Steven D'Aprano wrote:
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?


Probably the most pointless Python wart, I would think. The =/==
distinction makes sense in C, but since Python doesn't allow assignments
in expressions, I don't think there is any situation in which the distinction
is needed. Python could easily figure out whether you meant assignment
or equality from the context, just like the programmer does.

BASIC did it that way, IIRC. It always seemed like C was seriously twisted
for letting you get away with assignment in expressions in the first place.

I don't think Python's use of "==" has *ever* helped me find a bug, it
just creates them. I really think "=" ought to be accepted as well, and
"==" deprecated.

But, hey, nobody asked me, I guess. And it doesn't kill me to type the
extra "=". ;-)

Cheers,
Terry

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

Jul 19 '05 #75
Hallöchen!

Terry Hancock <ha*****@anansi spaceworks.com> writes:
[...]

BASIC did it that way, IIRC.
Right.
[...]

I don't think Python's use of "==" has *ever* helped me find a
bug, it just creates them. I really think "=" ought to be
accepted as well, and "==" deprecated.


However, then you must forbid a=b=1 for assigning to two variables
at the same time.

Tschö,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
Jul 19 '05 #76
On Sunday 26 June 2005 05:39 am, Torsten Bronger wrote:
Hallöchen!
However, then you must forbid a=b=1 for assigning to two variables
at the same time.


Why? It's already handled as an exception in the syntax.

In C, what you say makes sense, because "b=1" is an expression as
well as an assignment. But I don't think Python reads it that way -- it
just has code to recognize multiple assignment as a statement. I think
I remember reading that in the Language Reference or something.

Cheers,
Terry

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

Jul 19 '05 #77
Terry Hancock wrote:
On Sunday 26 June 2005 05:39 am, Torsten Bronger wrote:
Hallöchen!
However, then you must forbid a=b=1 for assigning to two variables
at the same time.


Why? It's already handled as an exception in the syntax.

In C, what you say makes sense, because "b=1" is an expression as
well as an assignment. But I don't think Python reads it that way -- it
just has code to recognize multiple assignment as a statement. I think
I remember reading that in the Language Reference or something.


You need to differentiate

a = b = 1

from

a = b == 1

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Jul 19 '05 #78
Terry Hancock wrote:
On Saturday 25 June 2005 01:08 pm, Steven D'Aprano wrote:
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?

Probably the most pointless Python wart, I would think. The =/==
distinction makes sense in C, but since Python doesn't allow assignments
in expressions, I don't think there is any situation in which the distinction
is needed. Python could easily figure out whether you meant assignment
or equality from the context, just like the programmer does.


There are situations where Python can't figure it out:
a = 1
b = 2
f = a == b
print a, b, f 1 2 False f = a = b
print a, b, f

2 2 2

--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton

Roel Schroeven
Jul 19 '05 #79
Steven D'Aprano <st***@REMOVETH IScyber.com.au> wrote:
Using := and = for assignment and equality is precisely as stupid as using
= and == for assignment and equality.


On the other hand, == is easier to type than := (two taps on the same key
vs two different keys, and at least on a US/English keyboard, no shift key
required). Not only that, but := is more likely to be turned into some
bizarre smiley face by brain-dead IM clients :-)
Jul 19 '05 #80

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
9639
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
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...
1
10080
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,...
1
7492
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
6733
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...
1
4043
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
2
3639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2874
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.