473,769 Members | 2,003 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 6127
"Konstantin Veretennicov" <kv***********@ gmail.com> wrote:
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'


Oops ! I've used filter only with lists and didn't know that it
preserves the type for strings and tuples. Here's a (hopefully) correct
version:

def filter(f,seq):
it = ifilter(f,seq)
if isinstance(seq, basestring):
return ''.join(it)
elif isinstance(seq, tuple):
return tuple(it)
else:
return list(it)
By the way, the documentation of filter is unclear on what is the
return type if seq is a subclass of list, tuple, str, or unicode; is it
type(seq) or the base builtin type ? Let's see:

def subclassFactory (cls):
return type("Dummy_" + cls.__name__, (cls,),
{'__new__' : lambda self, seq: cls.__new__(sel f, seq)})

baseToSub = dict([(base,subclassF actory(base))
for base in list,tuple,str, unicode])

f = lambda x: x.lower()
for Base,Sub in baseToSub.iteri tems():
assert type(__builtins __.filter(f, Sub('lowerUPPER Cap'))) is Base

for Base,Sub in baseToSub.iteri tems():
for cls in Base,Sub:
args = (f, cls('lowerUPPER Cap'))
assert filter(*args) == __builtins__.fi lter(*args)
George

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


Hmm... I used to be quite the fan of Python, yet not long ago I met
Ruby and fell in love almost instantly. Some of the features I like the
most:

- statement modifiers:

< "return a if a.value == true"
< "database.query (q) unless database.connec t == error
(etc)

- unless as "if not", since it gives nicer code to read

< unless false then print 1 # this prints 1 forever

- iterators, such as times (already mentioned)

- 'case'

< case var
< when 3 then do_sth
< when 4 then do_sth_else
< # etc...
< end

- everything returns a value, so you can do:

< foo = case foo2
< when 1 then yadda_yadda
< when 2 then blah_blah
< # etc
< end

And when foo2 == 2 then "blah_blah" gets executed and returned as the
'case' return value, thus assigning foo the value that results from
evaluating blah_blah

And some more, but those are the ones I like the best and python
doesn't have :-)

- greetings -
Nicolas

Jul 19 '05 #82
< "return a if a.value == true"
< "database.query (q) unless database.connec t == error
(etc)

if a.value == True:
return a

if not database.connec t == error:
database.query( q)

Trading two words for one word doesn't necessarily make the code
better.

< unless false then print 1 # this prints 1 forever
while not False:
print 1

"unless" seems to become "while not", as opposed to "if not". Should be
more consistent.

Jul 19 '05 #83
On Sun, 26 Jun 2005 14:30:15 +1000, Steven D'Aprano <st***@REMOVETH IScyber.com.au> wrote:
On Sat, 25 Jun 2005 23:08:10 +0000, Bengt Richter wrote:
[...]

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.

Point taken.
I understand how to manipulate __dict__ as an more complicated (dare I say
obfuscated?) way of assigning to object attributes.
Yes, it's a bit obfuscated.
[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 wouldn't do something unfortunate, would you? ;-)
I just wanted to clear them all at that point in the interaction.
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?

The only thing, ISTM, that would not also be unique in the with construct
is the function name, and you snipped the anonymnous def version that would
eliminate that. The main question in my mind would be binding of non-leading-dot
names. Would they work as in the suite of an "if" (i.e., binding in the same scope)
or as in a function with a new local scope that disappears on exit?

A function solves the alias name pollution problem, but prevents rebinding
anything external except explicitly declared globals, and closure cell vars
can't be rebound currently.
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.

I wonder what happens when you have multiple withs, e.g.,

with obj_a:
.x = 1
with obj_b:
.x = 2
.y = 3

(I guess you would have to have a stack with only the latest with effective).
whereas a simple aliasing syntax like

(a=obj_a, b=obj_b):
a.x = 1
b.x = 2
b.y = 3

is unambigous and concise and the scope of the namescan be limited
to prevent name pollution at compile time.

OTOH, what should
(a=obj_a):
a = 123 # XXX ??
mean? Should it mean obj_a=123 and rebind in that scope,
like a macro substitution of names at compile time?
I guess the corresponding with thing would be
with obj_a:
. = 123


Regards,
Bengt Richter
Jul 19 '05 #84
On Sun, 26 Jun 2005 14:36:42 +1000, Steven D'Aprano <st***@REMOVETH IScyber.com.au> wrote:
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 oops, for below example, needs global declaration
def foo():
global x
x:=123 #note that x:=123 searches outward through nested scopes,
#not including globals unless explicitly declared, whereas
# x=456 would always {re}bind the global x, as usual with a global x declared.
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 oops, not so, unless foo has correction above 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?

I forgot some of my previous thoughts on this. It's not as wild as it appears ;-)

I forgot to mention that of course a symbol found in __builtins__ by way
of the usual default lookup should not be rebound. And only globals explicitly
declared should be rebound (error in code above, since foo doesn't have global x).
So that limits it to the local scope and nested scopes and declared globals not
preempted by nearer nested scope variable names.

This is motivated by currently not being able to rebind a closure variable in
a nested scope, and the requirement of pre-existence within a limited range of
namespaces that can (I think ;-) be statically analyzed for is meant to prevent
new accidental collision problems.

Regards,
Bengt Richter
Jul 19 '05 #85
On Sunday 26 June 2005 06:11 am, Robert Kern wrote:
Terry Hancock wrote:
On Sunday 26 June 2005 05:39 am, Torsten Bronger wrote:
However, then you must forbid a=b=1 for assigning to two variables
at the same time.


You need to differentiate
a = b = 1
from
a = b == 1


Okay, I see what you mean. I can't ever recall having needed the
second form, though.

Of course, you could still do assignment like this:

a, b = (1,)*2

But I guess that's not exactly elegant. ;-)

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

Jul 19 '05 #86
Terry Hancock wrote:
On Sunday 26 June 2005 06:11 am, Robert Kern wrote:
Terry Hancock wrote:
On Sunday 26 June 2005 05:39 am, Torsten Bronger wrote:

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


Okay, I see what you mean. I can't ever recall having needed the
second form, though.


I use it all the time with Numeric's rich comparisons.

mask = some_arr == 999
Of course, you could still do assignment like this:

a, b = (1,)*2

But I guess that's not exactly elegant. ;-)


Ya think? :-)

--
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 #87
On Sun, 26 Jun 2005 23:22:00 -0500, Terry Hancock wrote:
You need to differentiate
a = b = 1
from
a = b == 1


Okay, I see what you mean. I can't ever recall having needed the
second form, though.

Of course, you could still do assignment like this:

a, b = (1,)*2

But I guess that's not exactly elegant. ;-)


In general that is not the same thing as a = b = obj.

py> a, b = ([], [])
py> a.append(1)
py> b
[]
py> a = b = []
py> a.append(1)
py> b
[1]
--
Steven.

Jul 19 '05 #88
Steven D'Aprano wrote:
On Sun, 26 Jun 2005 23:22:00 -0500, Terry Hancock wrote:
You need to differentiate
a = b = 1
from
a = b == 1


Okay, I see what you mean. I can't ever recall having needed the
second form, though.

Of course, you could still do assignment like this:

a, b = (1,)*2

But I guess that's not exactly elegant. ;-)


In general that is not the same thing as a = b = obj.

py> a, b = ([], [])
py> a.append(1)
py> b
[]
py> a = b = []
py> a.append(1)
py> b
[1]


What you wrote isn't, but what Terry wrote is.

In [1]: a, b = ([],)*2

In [2]: a.append(1)

In [3]: b
Out[3]: [1]

In [4]: a is b
Out[4]: True

--
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 #89
[Terry Hancock]
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.


That's what Python originally did, before release 0.9.6 (search
Misc/HISTORY for eqfix.py). Even this is ambigous then:

a = b

Especially at an interactive prompt, it's wholly ambiguous then
whether you want to change a's binding, or want to know whether a and
b compare equal.

Just yesterday, I wrote this in a script:

lastinline = ci == ncs - 1

This:

lastinline = ci = ncs - 1

means something very different (or means something identical,
depending on exactly how it is Python "could easily figure out" what I
intended <wink>).

Of course strange rules could have resolved this, like, say, "=" means
assignment, unless that would give a syntax error, and then "=" means
equality. Then

lastinline = ci = ncs - 1

would have been chained assignment, and something like

lastinline = (ci = ncs - 1)

would have been needed to get the intent of the current

lastinline = ci == ncs - 1
Jul 19 '05 #90

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

Similar topics

3
2825
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
3487
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
2170
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
9589
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
9423
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
10211
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
10045
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
9994
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
8872
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
3959
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
3562
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
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.