[OT-ish] Design principles: no bool arguments

2011-08-25 Thread Steven D'Aprano
One design principle often mentioned here (with a certain degree of
disagreement[1]) is the idea that as a general rule, you shouldn't write
functions that take a bool argument to switch between two slightly
different behaviours.

This is a principle often championed by the BDFL, Guido van Rossum.

Here's a Javascript-centric article which discusses the same idea, and gives
it a name: the Boolean Trap.

http://ariya.ofilabs.com/2011/08/hall-of-api-shame-boolean-trap.html

No doubt there are counter arguments as well. The most obvious to me is if
the flag=True and flag=False functions share a lot of code, it is poor
practice to implement them as two functions with two copies of almost
identical code.

My solution to this is a technical violation of the "Avoid Boolean Trap"
principle, but only in a private function:

def spam_on(arg):
 _spam(arg, True)

def spam_off(arg):
 _spam(arg, False)

def _spam(arg, flag):
do stuff
if flag:
a
else:
b
more stuff




[1] This is the Internet. There's *always* a certain amount of disagreement.


-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Design principles: no bool arguments

2011-08-25 Thread Maarten
On Aug 25, 9:13 am, Steven D'Aprano  wrote:
> One design principle often mentioned here (with a certain degree of
> disagreement[1]) is the idea that as a general rule, you shouldn't write
> functions that take a bool argument to switch between two slightly
> different behaviours.
>
> This is a principle often championed by the BDFL, Guido van Rossum.
>
> Here's a Javascript-centric article which discusses the same idea, and gives
> it a name: the Boolean Trap.
>
> http://ariya.ofilabs.com/2011/08/hall-of-api-shame-boolean-trap.html
>
> No doubt there are counter arguments as well. The most obvious to me is if
> the flag=True and flag=False functions share a lot of code, it is poor
> practice to implement them as two functions with two copies of almost
> identical code.

A simple one: C and C-like languages only have arguments, not keyword-
parameters. That alone makes a world of difference.

Maarten
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Design principles: no bool arguments

2011-08-25 Thread Stefan Behnel

Maarten, 25.08.2011 09:52:

On Aug 25, 9:13 am, Steven D'Aprano wrote:

One design principle often mentioned here (with a certain degree of
disagreement[1]) is the idea that as a general rule, you shouldn't write
functions that take a bool argument to switch between two slightly
different behaviours.

This is a principle often championed by the BDFL, Guido van Rossum.

Here's a Javascript-centric article which discusses the same idea, and gives
it a name: the Boolean Trap.

http://ariya.ofilabs.com/2011/08/hall-of-api-shame-boolean-trap.html

No doubt there are counter arguments as well. The most obvious to me is if
the flag=True and flag=False functions share a lot of code, it is poor
practice to implement them as two functions with two copies of almost
identical code.


A simple one: C and C-like languages only have arguments, not keyword-
parameters. That alone makes a world of difference.


Right. It's totally unreadable to find this in the code:

data1.merge_with(data2, true);

Requires you to either a) know the underlying signature by heart, or b) 
look it up before understanding the code.


It's a lot harder to argue against this:

data1.merge_with(data2, overwrite_duplicates=True)

Stefan

--
http://mail.python.org/mailman/listinfo/python-list


bash command, get stdErr

2011-08-25 Thread Tracubik
Hi all!
i'ld like to execute via Python this simple bash command:

sudo las

las is intended to be a typo for "ls"

the point is that i want to see in the terminal the stderr message (that 
is "sorry, try again" if i insert the wrong password or "sudo: las: 
command not found" otherwise)

i can simply do it with subprocess.POpen() or subprocess.Call() but as 
far as i know i have two choice: 
1) s = subprocess.Popen('sudo las', shell=True, stderr=subprocess.PIPE)

in this way i catch the stderr messages BUT they are not "printed" in the 
terminal

2) s = subprocess.Popen('sudo las', shell=True, stderr=none)
in this way i "print" the message in the terminal but i can retrieve they 
(the error messages) when the command is executed

it's important for me to know if the user have inserted the wrong 
password or i've tryied to execute a wrong/unsupported command (for 
example yum install in a ubuntu environment, or a typo like "las")

if i use stderr=subprocess.PIPE and the user insert a wrong password, 
he'll get a second request of insert password without the reason for 
doing it (because the error message isn't printed on the terminal). This 
is not a big problem, he will understand he haven't inserted the right 
password, and if he miss the password 3 times i'll pop-up a gtk alert 
windows to inform him of the problem. Still, it's not good to don't give 
feedback of the error to the user, so i'ld like to print the stderr on 
terminal AND get it after the command terminate to check the problem 
occurred (exit status is not enough).

Is there a way to accomplish this?
As usual sorry for my bad english
MedeoTL 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bash command, get stdErr

2011-08-25 Thread Chris Rebert
On Thu, Aug 25, 2011 at 1:25 AM, Tracubik  wrote:
> Hi all!
> i'ld like to execute via Python this simple bash command:
>
> sudo las
>
> las is intended to be a typo for "ls"
>
> the point is that i want to see in the terminal the stderr message (that
> is "sorry, try again" if i insert the wrong password or "sudo: las:
> command not found" otherwise)
>
> i can simply do it with subprocess.POpen() or subprocess.Call() but as
> far as i know i have two choice:
> 1) s = subprocess.Popen('sudo las', shell=True, stderr=subprocess.PIPE)
>
> in this way i catch the stderr messages BUT they are not "printed" in the
> terminal
>
> 2) s = subprocess.Popen('sudo las', shell=True, stderr=none)
> in this way i "print" the message in the terminal but i can retrieve they
> (the error messages) when the command is executed

> Still, it's not good to don't give
> feedback of the error to the user, so i'ld like to print the stderr on
> terminal AND get it after the command terminate to check the problem
> occurred (exit status is not enough).

Untested:

from subprocess import Popen, PIPE
sudo = Popen("sudo las", shell=True, stderr=PIPE)
tee = Popen(["tee", "/dev/stderr"], stdin=sudo.stderr, stdout=PIPE)
# Read from tee.stdout to get any error messages

Further info: http://en.wikipedia.org/wiki/Tee_%28command%29

Cheers,
Chris
--
http://rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Design principles: no bool arguments

2011-08-25 Thread Thomas 'PointedEars' Lahn
Stefan Behnel wrote:

> Maarten, 25.08.2011 09:52:
>> On Aug 25, 9:13 am, Steven D'Aprano wrote:
>>> One design principle often mentioned here (with a certain degree of
>>> disagreement[1]) is the idea that as a general rule, you shouldn't write
>>> functions that take a bool argument to switch between two slightly
>>> different behaviours.
>>>
>>> This is a principle often championed by the BDFL, Guido van Rossum.
>>>
>>> Here's a Javascript-centric article which discusses the same idea, and
>>> gives it a name: the Boolean Trap.
>>>
>>> http://ariya.ofilabs.com/2011/08/hall-of-api-shame-boolean-trap.html
>>>
>>> No doubt there are counter arguments as well. The most obvious to me is
>>> if the flag=True and flag=False functions share a lot of code, it is
>>> poor practice to implement them as two functions with two copies of
>>> almost identical code.
>>
>> A simple one: C and C-like languages only have arguments, not keyword-
>> parameters. That alone makes a world of difference.

The logic is flawed, for one because keyword arguments can be emulated.
For example in C, you can (and would) OR-combine binary flag constants:

  open("foo", O_RDONLY);

instead of

  open("foo", TRUE);

(assuming the latter function existed).  Other approaches can be found in C 
as well:

  fopen("foo", "r");

In ECMAScript implementations like JavaScript (which I count as C-like), you 
can define the API so that it accepts object references (as explained in the 
article):

  foo(bar, {baz: true});

instead of (or in addition to)

  foo(bar, true);

(But this is a trade-off readability vs. runtime and memory efficiency, as 
each time the function is called an object needs to be created, if it is not 
cached, and an additional property access is necessary in the 
function/method.  Python has much the same problem, see below.)

And there can hardly be an argument that W3C DOM Level 3 Events init…Event() 
methods are *unnecessarily* FUBAR.  Even OMG IDL supports constants (as 
showed by the HTMLElement interface of DOM Level 2 Core), and passing of 
object instances to methods.
 
> Right. It's totally unreadable to find this in the code:
> 
>  data1.merge_with(data2, true);
> 
> Requires you to either a) know the underlying signature by heart, or b)
> look it up before understanding the code.
> 
> It's a lot harder to argue against this:
> 
>  data1.merge_with(data2, overwrite_duplicates=True)

Both variants work (even in Py3) if you only define

class Data(object):
  def merge_with(self, bar, overwrite_duplicates):
pass

data1 = Data()
data2 = Data()

You have to define

class Data(object):
  def merge_with(self, bar, **kwargs):
# do something with kwargs['overwrite_duplicates']
pass

data1 = Data()
data2 = Data()

so that

data1.merge_with(data2, True);

is a syntax error ("TypeError: merge_with() takes exactly 2 arguments (3 
given)").

IOW, this advantage of Python in readability is not only caused by API 
definition, but also by how the API is used.  It might turn into a 
disadvantage if key lookups make the code expensive memory- and runtime 
wise.

And you will still have to know the underlying signature to name the 
argument.  Worse, with keyword arguments you *have to* look up the 
documentation (i. e., it needs to be well-documented as well) to know its 
name (as the compiler can only tell you "kwargs").

So no doubt there are advantages to keyword arguments, but there are 
disadvantages, too.

-- 
PointedEars

Bitte keine Kopien per E-Mail. / Please do not Cc: me.
-- 
http://mail.python.org/mailman/listinfo/python-list


PUT with proxy-support

2011-08-25 Thread Shashwat Anand
I want to make a PUT request.
I need some headers of my own ( certificates etc ) and I need to mandatorily
use a proxy.
Also the url is of the form http://www.xyz.com/abc and I don't have
permission to put data
on http://www.xyz.com while I do have permission to put data on
http://www.xyz.com/abc

I tried httplib, httplib2, urllib2 with no avail.
I managed to do this via command line curl:

$ curl http:/xyz.com/testing/shashwat/test.txt -T test.txt -H "sw-version:
1.0" -H
"CA-Cert-Auth:v=1;a=yxyz.prod;h=10.10.0.1;t=1316594650;s=.AeEYJMMfElN74fnWD3GlXJ4J.1KiQFg--"
--proxy proxy.xyz.com:3128 -H "Content-Type:text/plain"

Is there a way to do it in python apart from using command line curl in
python.
The machine is RHEL4 and is giving hard time installing pycurl.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PUT with proxy-support

2011-08-25 Thread Thomas Jollans
On 25/08/11 13:07, Shashwat Anand wrote:
> I want to make a PUT request.
> I need some headers of my own ( certificates etc ) and I need to
> mandatorily use a proxy.
> Also the url is of the form http://www.xyz.com/abc and I don't have
> permission to put data
> on http://www.xyz.com while I do have permission to put data
> on http://www.xyz.com/abc
> 
> I tried httplib, httplib2, urllib2 with no avail.

What did you try? What problems did you run into?

I'm sure there is a way in Python, and chances are you were already
close to finding it -- show us what you tried, what actually happened,
including any error messages in full, and what you wanted to happen.

Thomas


> I managed to do this via command line curl:
> 
> $ curl http:/xyz.com/testing/shashwat/test.txt
>  -T test.txt -H "sw-version:
> 1.0" -H
> "CA-Cert-Auth:v=1;a=yxyz.prod;h=10.10.0.1;t=1316594650;s=.AeEYJMMfElN74fnWD3GlXJ4J.1KiQFg--"
> --proxy proxy.xyz.com:3128  -H
> "Content-Type:text/plain"
> 
> Is there a way to do it in python apart from using command line curl in
> python.
> The machine is RHEL4 and is giving hard time installing pycurl.
> 
> 
> 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PUT with proxy-support

2011-08-25 Thread Shashwat Anand
On Thu, Aug 25, 2011 at 4:48 PM, Thomas Jollans  wrote:

> On 25/08/11 13:07, Shashwat Anand wrote:
> > I want to make a PUT request.
> > I need some headers of my own ( certificates etc ) and I need to
> > mandatorily use a proxy.
> > Also the url is of the form http://www.xyz.com/abc and I don't have
> > permission to put data
> > on http://www.xyz.com while I do have permission to put data
> > on http://www.xyz.com/abc
> >
> > I tried httplib, httplib2, urllib2 with no avail.
>
> What did you try? What problems did you run into?
>
> I'm sure there is a way in Python, and chances are you were already
> close to finding it -- show us what you tried, what actually happened,
> including any error messages in full, and what you wanted to happen.
>
> Thomas
>

Hi Thomas,
so one of my tries was:

import urllib
import urllib2
import httplib
import httplib2

url = 'http://alatheia.zenfs.com/testing/shashwat'
body_content = 'CONTENT GOES HERE'
proxy = 'ca-proxy.corp.xyz.com:3128'

params = {
'x-sws-version' : '1.0',
'x-sws-access' : 'public',
'User-Agent' : 'CacheSystem',
'Cache-Control' : 'public',
'Content-Type' : 'text/plain',
'App-Auth' :
'v=1;a=client.alatheia.prod;h=10.16.19.23;t=1316594650;s=AeEYJMMfElN74fnWD3GlXJ4J.1KiQFg--',
   }

httplib2.debuglevel=4
h = httplib2.Http(proxy_info = httplib2.ProxyInfo(3, '
ca-proxy.corp.xyz.com:3128', 3128))
resp, content = h.request(url, "PUT", body=body_content, headers = params)
print resp
print content

Output:

connect: (alatheia.zenfs.com, 80)
Traceback (most recent call last):
  File "test.py", line 29, in 
resp, content = h.request(url, "PUT", body=body_content, headers =
params)
  File "/home/y/lib/python2.6/site-packages/httplib2/__init__.py", line
1436, in request
(response, content) = self._request(conn, authority, uri, request_uri,
method, body, headers, redirections, cachekey)
  File "/home/y/lib/python2.6/site-packages/httplib2/__init__.py", line
1188, in _request
(response, content) = self._conn_request(conn, request_uri, method,
body, headers)
  File "/home/y/lib/python2.6/site-packages/httplib2/__init__.py", line
1123, in _conn_request
conn.connect()
  File "/home/y/lib/python2.6/site-packages/httplib2/__init__.py", line 786,
in connect
self.sock.connect(sa)
  File "/home/y/lib/python2.6/site-packages/httplib2/socks.py", line 381, in
connect
self.__negotiatehttp(destpair[0], destpair[1])
  File "/home/y/lib/python2.6/site-packages/httplib2/socks.py", line 347, in
__negotiatehttp
raise HTTPError((statuscode, statusline[2]))
httplib2.socks.HTTPError: (403, 'Tunnel or SSL Forbidden')

The reason I can trace it is because,
I can use PUT on http://alatheia.zenfs.com/testing/shashwat but not on
http://alatheia.zenfs.com/ however host is resolved.
Again port 80 is used even when I use specific port (3128, in this case).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PUT with proxy-support

2011-08-25 Thread Shashwat Anand
On Thu, Aug 25, 2011 at 4:48 PM, Max Countryman  wrote:

> Check out the python Requests module:
> http://docs.python-requests.org/en/latest/index.html
>
>
Python request module is not documented very well IMHO.
I tried to figure how to make PUT calls, how to add proxy, how to add
certificates in headers.
Did not managed to find all of it.
Am not sure is supports REST calls with proxy support.



> Sent from my iPhone
>
> On Aug 25, 2011, at 7:07, Shashwat Anand  wrote:
>
> I want to make a PUT request.
> I need some headers of my own ( certificates etc ) and I need to
> mandatorily use a proxy.
> Also the url is of the form http://www.xyz.com/abcand 
> I don't have permission to put data
> on  http://www.xyz.com while I do have permission to
> put data on  http://www.xyz.com/abc
>
> I tried httplib, httplib2, urllib2 with no avail.
> I managed to do this via command line curl:
>
> $ curl http:/ 
> xyz.com/testing/shashwat/test.txt -T test.txt -H "sw-version: 1.0" -H
> "CA-Cert-Auth:v=1;a=yxyz.prod;h=10.10.0.1;t=1316594650;s=.AeEYJMMfElN74fnWD3GlXJ4J.1KiQFg--"
> --proxy proxy.xyz.com:3128 -H "Content-Type:text/plain"
>
> Is there a way to do it in python apart from using command line curl in
> python.
> The machine is RHEL4 and is giving hard time installing pycurl.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PUT with proxy-support

2011-08-25 Thread Laszlo Nagy



I tried httplib, httplib2, urllib2 with no avail.
I managed to do this via command line curl:

$ curl http:/xyz.com/testing/shashwat/test.txt 
 -T test.txt -H "sw-version: 
1.0" -H 
"CA-Cert-Auth:v=1;a=yxyz.prod;h=10.10.0.1;t=1316594650;s=.AeEYJMMfElN74fnWD3GlXJ4J.1KiQFg--" 
--proxy proxy.xyz.com:3128  -H 
"Content-Type:text/plain"
If you can do it with command line curl then probably you can do it with 
pycurl.


http://pycurl.sourceforge.net/

Best,

   Laszlo

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PUT with proxy-support

2011-08-25 Thread Shashwat Anand
On Thu, Aug 25, 2011 at 5:22 PM, Laszlo Nagy  wrote:

> **
>
>  I tried httplib, httplib2, urllib2 with no avail.
> I managed to do this via command line curl:
>
>  $ curl http:/xyz.com/testing/shashwat/test.txt -T test.txt -H
> "sw-version: 1.0" -H
> "CA-Cert-Auth:v=1;a=yxyz.prod;h=10.10.0.1;t=1316594650;s=.AeEYJMMfElN74fnWD3GlXJ4J.1KiQFg--"
> --proxy proxy.xyz.com:3128 -H "Content-Type:text/plain"
>
> If you can do it with command line curl then probably you can do it with
> pycurl.
>
> http://pycurl.sourceforge.net/
>

Yeah.
I tried that.
The system is RHEL 4.

So it gave me this error :
src/pycurl.c:42:20: Python.h: No such file or directory
src/pycurl.c:43:22: pythread.h: No such file or directory
src/pycurl.c:58:4: #error "Need Python version 2.2 or greater to compile
pycurl."
src/pycurl.c:61:4: #error "Need libcurl version 7.19.0 or greater to compile
pycurl."

Apparently we need python-devel package.
Following http://fedoraproject.org/wiki/EPEL/FAQ#howtouse I added EPEL
software repository.

sh-3.00$ yum list | grep -i python-dev
sh-3.00$ sudo yum -y install python-dev
Password:
Setting up Install Process
Setting up repositories
epel [1/1]
epel  100% |=| 3.8 kB00:00

Reading repository metadata in from local files
b1f7bfef07466e9561644aba7 100% |=| 841 kB00:06

epel  : ## 2583/2583
Added 2583 new packages, deleted 0 old in 4.51 seconds
Parsing package install arguments
No Match for argument: python-dev
Nothing to do

Turned out that python-curl is the required package which is already
installed.
Still no use.

sh-3.00$ yum list | grep -i python-curl
python-curl.x86_64   7.12.1-1.3.el4.rf  installed

sh-3.00$ python
Python 2.6.4 (r264:75706, Nov  9 2009, 16:32:06)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pycurl
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named pycurl
>>>

Tried installing via easy_install

sh-3.00$ sudo easy_install pycurl

Searching for pycurl
Reading http://pypi.python.org/simple/pycurl/
Reading http://pycurl.sourceforge.net/
Reading http://pycurl.sourceforge.net/download/
Best match: pycurl 7.19.0
Downloading http://pycurl.sourceforge.net/download/pycurl-7.19.0.tar.gz
Processing pycurl-7.19.0.tar.gz
Running pycurl-7.19.0/setup.py -q bdist_egg --dist-dir
/tmp/easy_install-2ZCa8v/pycurl-7.19.0/egg-dist-tmp-DyHFls
Using curl-config (libcurl 7.12.1)
src/pycurl.c:42:20: Python.h: No such file or directory
src/pycurl.c:43:22: pythread.h: No such file or directory
src/pycurl.c:58:4: #error "Need Python version 2.2 or greater to compile
pycurl."
src/pycurl.c:61:4: #error "Need libcurl version 7.19.0 or greater to compile
pycurl."
[... Error Clipped]
error: Setup script exited with error: command '/usr/bin/gcc' failed with
exit status 1



>
> Best,
>
>Laszlo
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PUT with proxy-support

2011-08-25 Thread Max Countryman
Check out the python Requests module: 
http://docs.python-requests.org/en/latest/index.html

Sent from my iPhone

On Aug 25, 2011, at 7:07, Shashwat Anand  wrote:

> I want to make a PUT request.
> I need some headers of my own ( certificates etc ) and I need to mandatorily 
> use a proxy.
> Also the url is of the form http://www.xyz.com/abc and I don't have 
> permission to put data
> on http://www.xyz.com while I do have permission to put data on 
> http://www.xyz.com/abc
> 
> I tried httplib, httplib2, urllib2 with no avail.
> I managed to do this via command line curl:
> 
> $ curl http:/xyz.com/testing/shashwat/test.txt -T test.txt -H "sw-version: 
> 1.0" -H 
> "CA-Cert-Auth:v=1;a=yxyz.prod;h=10.10.0.1;t=1316594650;s=.AeEYJMMfElN74fnWD3GlXJ4J.1KiQFg--"
>  --proxy proxy.xyz.com:3128 -H "Content-Type:text/plain"
> 
> Is there a way to do it in python apart from using command line curl in 
> python.
> The machine is RHEL4 and is giving hard time installing pycurl.
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


How to run a setup command with 'pip install'?

2011-08-25 Thread Andrei
Hello,

I have a trouble installing the DMSL package with pip. The package doesn't have 
*.c files, which must be produced with Cython by 'pyhton setup.py build_ext' 
command. How do I run it with 'pip install'?

Please see http://stackoverflow.com/questions/7189336/ for details.

Regards,
Andrei
-- 
http://mail.python.org/mailman/listinfo/python-list


Immediate Requirement for a Data Warehouse Developer

2011-08-25 Thread Sirisha
Position Profile – Senior Data Warehouse Developer
Location: Detroit, MI
Contact: Please send resumes to resu...@rg-llc.com or call
313.254.4631

Purpose

   Assist with analysis, design, development and implementation of
projects for the corporate data warehouse
   Partner with the DBA team and other data warehouse developers to
achieve the best performance and efficiency possible for our internal
business customers
   Act as the Subject Matter Expert in methods, best practices and
standards related to data management, data movement, conceptual and
physical database design, and data warehousing business intelligence
technologies

Basic Position Requirements: What do you need to qualify as a
candidate for this position?
   You need to be organized, with an ability to multi-task and
prioritize multiple requests
   You need to be able to demonstrate problem-solving skills and make
quick decisions
   You need to be self-driven, motivated to help,  and able to perform
with minimal supervision in a team environment
   You need to be receptive to ongoing feedback aimed at improving the
performance of you and your team

Requirements: Experience and Education requirements.
Required:
   Minimum of 5 years of data warehouse analysis, design and
development experience
   Minimum of 10 years of overall Information Systems experience
   Practical expertise in full lifecycle database design, including 3NF
and dimensional design concepts
   Proficiency in PL/SQL coding, troubleshooting, and performance
tuning
   Experience with Oracle, preferably version 10/11
Preferred
   Experience in DW specific disciplines such as Data Quality and
Cleansing, Data Governance, Metadata usage and management, and Master
data management.
   Knowledge of ETL tools – specifically Oracle Data Integrator
Enterprise Edition
   Knowledge of Unix Scripting and job scheduling
   Bachelor’s degree

Position Outcomes & Activities: You will be measured on your ability
to perform the following activities effectively
   Gather requirements:  You will need to meet with internal customers
so you can provide analysis and solution design to meet their
requirements.
   Provide time and cost estimates:  You will be measured on your
ability to estimate time and cost for architecture design and
development on data warehouse projects
   Provide recommendations and Implement:  As the Subject Matter Expert
you will be expected to make recommendations on system and
architecture changes to improve performance and efficiency and see
these recommendation through to implementation
   Complete development:  You will need to develop solutions using
Oracle, PL/SQL, Oracle Data Integrator Enterprise Edition (ODIEE).

Please send resumes to resu...@rg-llc.com or call 313.254.4631
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to run a setup command with 'pip install'?

2011-08-25 Thread Andrei
'pip install pyrex' solved the problem (credit to @jezdez)
-- 
http://mail.python.org/mailman/listinfo/python-list


Getting a module's code object

2011-08-25 Thread Arnaud Delobelle
Hi all,

In Python 3, a function f's code object can be accessed via f.__code__.

I'm interested in getting a module's code object, i.e. the code that
is executed when the module is run.  I don't think it's accessible via
the module object itself (although I would be glad if somebody proved
me wrong :).  In the marshal module docs [1] it is mentioned that:

"""
The marshal module exists mainly to support reading and writing the
“pseudo-compiled” code for Python modules of .pyc files.
"""

So it seems that the module's code object is marshalled into the .pyc
file - so there may be a way to unmarshal it - but I can't easily find
information about how to do this.

Is this a good lead, or is there another way to obtained a module's code object?

Thanks

-- 
Arnaud

[1] http://docs.python.org/py3k/library/marshal.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Run time default arguments

2011-08-25 Thread ting
What is the most common way to handle default function arguments that
are set at run time, rather than at compile time? The snippet below is
the current technique that I've been using, but it seems inelegant.

defaults = { 'debug' : false }
def doSomething (debug = None):
debug = debug if debug != None else defaults['debug']
# blah blah blah

Basically, I want to define a set of common defaults at the module and/
or class level but let them be overridden via function arguments. The
simpler, naive approach does not work, because the argument gets set
at compile time, rather than at run time. That is:
def doSomething(debug = defaults['debug'])
ends up being compiled into:
def doSomething(debug = false)
which is not the behavior I want, as I want to evaluate the argument
at run time.

Any better suggestions?
--
// T.Hsu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Run time default arguments

2011-08-25 Thread Arnaud Delobelle
On Aug 25, 3:30 pm, t...@thsu.org wrote:
> What is the most common way to handle default function arguments that
> are set at run time, rather than at compile time? The snippet below is
> the current technique that I've been using, but it seems inelegant.
>
> defaults = { 'debug' : false }
> def doSomething (debug = None):
>     debug = debug if debug != None else defaults['debug']
>     # blah blah blah

You're close to the usual idiom:

def doSomething(debug=None):
if debug is None:
debug = defaults['debug']
...

Note the use of 'is' rather than '=='
HTH

--
Arnaud
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Run time default arguments

2011-08-25 Thread MRAB

On 25/08/2011 15:30, t...@thsu.org wrote:

What is the most common way to handle default function arguments that
are set at run time, rather than at compile time? The snippet below is
the current technique that I've been using, but it seems inelegant.

defaults = { 'debug' : false }
def doSomething (debug = None):
 debug = debug if debug != None else defaults['debug']
 # blah blah blah

Basically, I want to define a set of common defaults at the module and/
or class level but let them be overridden via function arguments. The
simpler, naive approach does not work, because the argument gets set
at compile time, rather than at run time. That is:
 def doSomething(debug = defaults['debug'])
ends up being compiled into:
 def doSomething(debug = false)
which is not the behavior I want, as I want to evaluate the argument
at run time.

Any better suggestions?


The recommended way is:

def doSomething (debug = None):
if debug is None:
debug = defaults['debug']

It's more lines, but clearer.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Immediate Requirement for a Data Warehouse Developer

2011-08-25 Thread Philip Semanchuk

On Aug 25, 2011, at 9:24 AM, Sirisha wrote:

> Position Profile – Senior Data Warehouse Developer

As was mentioned on the list less than 24 hours ago, please don't post job 
listings to this mailing list. Use the Python jobs board instead:
http://www.python.org/community/jobs/


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT-ish] Design principles: no bool arguments

2011-08-25 Thread Terry Reedy

On 8/25/2011 3:13 AM, Steven D'Aprano wrote:

One design principle often mentioned here (with a certain degree of
disagreement[1]) is the idea that as a general rule, you shouldn't write
functions that take a bool argument to switch between two slightly
different behaviours.

This is a principle often championed by the BDFL, Guido van Rossum.


You missed the essential caveat to his rule. See below.


Here's a Javascript-centric article which discusses the same idea, and gives
it a name: the Boolean Trap.

http://ariya.ofilabs.com/2011/08/hall-of-api-shame-boolean-trap.html


This was mostly about defining parameters as positional-only (which 
Python does not have) versus keyword-optional or keyword only. In 
Python, callers always have the 'keyword = BOOL' option.



No doubt there are counter arguments as well. The most obvious to me is if
the flag=True and flag=False functions share a lot of code, it is poor
practice to implement them as two functions with two copies of almost
identical code.

My solution to this is a technical violation of the "Avoid Boolean Trap"
principle, but only in a private function:

def spam_on(arg):
  _spam(arg, True)

def spam_off(arg):
  _spam(arg, False)

def _spam(arg, flag):
 do stuff
 if flag:
 a
 else:
 b
 more stuff


As I think one of the comments pointed out, this now means that if I the 
user need to compute whether to turn off or on, I now have to write


if expr: spam_on(arg)
elses: spam_off(arg)

(or put this on 4 lines if you prefer ;-) instead of

spam_switch(expr, arg)

so moving the conditional out of the function *pushes it onto every 
user*. Note that naming the function 'switch' and putting the bool as 
the first param makes it pretty obvious that True=='on', and False=='off'.


As I remember, Guido only recommendeds splitting if the boolean arg is 
(would be) always (nearly) passed as a constant True or False. Of 
course, I am not sure how one forsees that at the design stage, prior to 
field use.


--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a module's code object

2011-08-25 Thread Peter Otten
Arnaud Delobelle wrote:

> In Python 3, a function f's code object can be accessed via f.__code__.
> 
> I'm interested in getting a module's code object, i.e. the code that
> is executed when the module is run.  I don't think it's accessible via
> the module object itself (although I would be glad if somebody proved
> me wrong :).  In the marshal module docs [1] it is mentioned that:
> 
> """
> The marshal module exists mainly to support reading and writing the
> “pseudo-compiled” code for Python modules of .pyc files.
> """
> 
> So it seems that the module's code object is marshalled into the .pyc
> file - so there may be a way to unmarshal it - but I can't easily find
> information about how to do this.
> 
> Is this a good lead, or is there another way to obtained a module's code
> object?

Taken from pkgutil.py:

def read_code(stream):
# This helper is needed in order for the PEP 302 emulation to
# correctly handle compiled files
import marshal

magic = stream.read(4)
if magic != imp.get_magic():
return None

stream.read(4) # Skip timestamp
return marshal.load(stream)

Alternatively you can compile the source yourself:

module = compile(source, filename, "exec")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a module's code object

2011-08-25 Thread Arnaud Delobelle
On 25 August 2011 16:07, Peter Otten <__pete...@web.de> wrote:
> Arnaud Delobelle wrote:
>
>> In Python 3, a function f's code object can be accessed via f.__code__.
>>
>> I'm interested in getting a module's code object,
[...]
>
> Taken from pkgutil.py:
>
> def read_code(stream):
>    # This helper is needed in order for the PEP 302 emulation to
>    # correctly handle compiled files
>    import marshal
>
>    magic = stream.read(4)
>    if magic != imp.get_magic():
>        return None
>
>    stream.read(4) # Skip timestamp
>    return marshal.load(stream)

This works fine, thanks a lot!

> Alternatively you can compile the source yourself:
>
> module = compile(source, filename, "exec")

I don't necessarily have access to the source file.

-- 
Arnaud
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Design principles: no bool arguments

2011-08-25 Thread Stefan Behnel

Thomas 'PointedEars' Lahn, 25.08.2011 11:29:

Stefan Behnel wrote:

It's totally unreadable to find this in the code:

  data1.merge_with(data2, true);

Requires you to either a) know the underlying signature by heart, or b)
look it up before understanding the code.

It's a lot harder to argue against this:

  data1.merge_with(data2, overwrite_duplicates=True)

[...]
And you will still have to know the underlying signature to name the
argument.  Worse, with keyword arguments you *have to* look up the
documentation (i. e., it needs to be well-documented as well) to know its
name (as the compiler can only tell you "kwargs").


Note that code is read more often than it gets written.

Stefan

--
http://mail.python.org/mailman/listinfo/python-list


Disable pop up menu that triggers upon pressing tab,

2011-08-25 Thread Emory Watts
Hello, I tried to find out how to do this on my own, but searching around
turned up no results. And this is the only way I saw to get a question
answered. I would like know how to disable the pop up predictions menu that
appears when I press tab. I would much rather just be able to tab over, and
I cannot figure out how to disable the menu. Thank you for your time.

Emory
-- 
http://mail.python.org/mailman/listinfo/python-list


Python-URL! - weekly Python news and links (Aug 25)

2011-08-25 Thread Cameron Laird
[Original draft by Gabriel Genellina.]

QOTW:  "Python is a programming language, not an ice cream shop." -
Steven
D'Aprano, 2011-08-10, on providing the language with just "more
choices"


   Comparing the relative speed of `i += 1` and `i = i + 1`
   
http://groups.google.com/group/comp.lang.python/browse_thread/thread/db68a23685eb03a9/

   Efficiently split and process a large string:
   
http://groups.google.com/group/comp.lang.python/browse_thread/thread/f9122961559e747b/

   Fastest way to do string concatenation:
   
http://groups.google.com/group/comp.lang.python/browse_thread/thread/f65e05cd3a230290/

   An unexpected interaction between function scope and class
namespace:
   
http://groups.google.com/group/comp.lang.python/browse_thread/thread/9c4435d56fdec152/

   The GIL, once again:
   http://mail.python.org/pipermail/python-dev/2011-August/112813.html

   Three language proposals:
   allow line breaks at operators (very long thread!):
   
http://groups.google.com/group/comp.lang.python/browse_thread/thread/a80ffc70aeea2116/
   repeat the right hand side value of assignment statements, as
needed:
   
http://groups.google.com/group/comp.lang.python/browse_thread/thread/6cf460dc9d6262d1/
   issue warnings when builtin names are hidden:
   
http://groups.google.com/group/comp.lang.python/browse_thread/thread/1b2dd8552aabf033/

   How to generate and send mails: a step by step tutorial
   
http://groups.google.com/group/comp.lang.python/browse_thread/thread/e0793c1007361398/

   Best practices when dealing with unknown exceptions:
   
http://groups.google.com/group/comp.lang.python/browse_thread/thread/d8da925e6fa03ec6/

   When using extended slicing, behavior of negative stop values is
not fully
   intuitive:
   
http://groups.google.com/group/comp.lang.python/browse_thread/thread/29193779abef5bfb/

   It's not easy to check a folder for write access on Windows:
   
http://groups.google.com/group/comp.lang.python/browse_thread/thread/122a47fce5571322/

   Advice on how long a function should be:
   
http://groups.google.com/group/comp.lang.python/browse_thread/thread/97076160ebf0f392/

   It is relatively easy to confuse the import machinery and make
import fail:
   
http://groups.google.com/group/comp.lang.python/browse_thread/thread/d3199d1e000b135d/

   Non-local variables and exec/eval: a clarification
   
http://groups.google.com/group/comp.lang.python/browse_thread/thread/9f46a4b59f525f59/

   An original idea: pure-python templates using the AST
   
http://groups.google.com/group/comp.lang.python/browse_thread/thread/827f4345d4ad5672/



Everything Python-related you want is probably one or two clicks away
in
these pages:

   Python.org's Python Language Website is the traditional
   center of Pythonia
   http://www.python.org
   Notice especially the master FAQ
   http://www.python.org/doc/FAQ.html

   Just beginning with Python?  This page is a great place to start:
   http://wiki.python.org/moin/BeginnersGuide/Programmers

   Planet Python:  you want to visit there:
   http://planet.python.org
   But don't confuse it with Planet SciPy:
   http://planet.scipy.org
   And don't confuse *that* with SciPyTip, a high-quality daily (!)
tip
   for the numerically-inclined:
   http://twitter.com/SciPyTip

   Python Insider is the official blog of the Python core development
   team:
   
http://pyfound.blogspot.com/2011/03/python-dev-launches-python-insider-blog.html

   The Python Software Foundation (PSF) has replaced the Python
   Consortium as an independent nexus of activity.  It has official
   responsibility for Python's development and maintenance.
   http://www.python.org/psf/
   Among the ways you can support PSF is with a donation.
   http://www.python.org/psf/donations/
   Keep up with the PSF at "Python Software Foundation News":
   http://pyfound.blogspot.com

   The Python Papers aims to publish "the efforts of Python
enthusiasts":
   http://pythonpapers.org/

   Doug Hellman's "Module of the week" is essential reading:
   http://www.doughellmann.com/PyMOTW/

   comp.lang.python.announce announces new Python software.  Be
   sure to scan this newsgroup weekly.
   http://groups.google.com/group/comp.lang.python.announce/topics

   Python411 indexes "podcasts ... to help people learn Python ..."
   Updates appear more-than-weekly:
   http://www.awaretek.com/python/index.html

   The Python Package Index catalogues packages.
   http://www.python.org/pypi/

   Much of Python's real work takes place on Special-Interest Group
   mailing lists
   http://www.python.org/sigs/

   Python Success Stories--from air-traffic control to on-line
   match-making--can inspire you or decision-makers to whom you're
   subject with a vision of what the language makes practical.
   http://w

Re: Design principles: no bool arguments

2011-08-25 Thread Thomas 'PointedEars' Lahn
Stefan Behnel wrote:

> Thomas 'PointedEars' Lahn, 25.08.2011 11:29:
>> Stefan Behnel wrote:
>>> It's totally unreadable to find this in the code:
>>>
>>>   data1.merge_with(data2, true);
>>>
>>> Requires you to either a) know the underlying signature by heart, or b)
>>> look it up before understanding the code.
>>>
>>> It's a lot harder to argue against this:
>>>
>>>   data1.merge_with(data2, overwrite_duplicates=True)
>>[...]
>> And you will still have to know the underlying signature to name the
>> argument.  Worse, with keyword arguments you *have to* look up the
>> documentation (i. e., it needs to be well-documented as well) to know its
>> name (as the compiler can only tell you "kwargs").
> 
> Note that code is read more often than it gets written.

It is not clear to me why you completely ignored the rest of my
counter-argument.  As it is, yours is a weak argument.

-- 
PointedEars

Bitte keine Kopien per E-Mail. / Please do not Cc: me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Disable pop up menu that triggers upon pressing tab,

2011-08-25 Thread Chris Rebert
On Thu, Aug 25, 2011 at 11:43 AM, Emory Watts  wrote:
> Hello, I tried to find out how to do this on my own, but searching around
> turned up no results. And this is the only way I saw to get a question
> answered. I would like know how to disable the pop up predictions menu that
> appears when I press tab. I would much rather just be able to tab over, and
> I cannot figure out how to disable the menu. Thank you for your time.

 Which of the myriad Python editors or interpreters is your question
in regards to?

Cheers,
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Adding a ranking based on two fields

2011-08-25 Thread noydb
Hello All,

Looking for some advice/ideas on how to implement a ranking to a
'scores' field I have.  So this scores field has values ranging from
1.00-4.  There is also a count field.  I want to add a rank field such
that all the records have a unique ranking, 1 through the number of
records (thousands).  The rank is based on the score first, the count
second.  So, a record with a score of 4 and a count of 385 is ranked
higher than a record with a score of 4 and a count of 213 AND higher
than record with a score of 3.25 with a count of 4640.

My thought was to add the unique score values to a list and loop thru
the list... sort records with score=listItem, add ranking... not quite
sure how to do this!

Any help would be much appreciated!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding a ranking based on two fields

2011-08-25 Thread Chris Rebert
On Thu, Aug 25, 2011 at 1:38 PM, noydb  wrote:
> Hello All,
>
> Looking for some advice/ideas on how to implement a ranking to a
> 'scores' field I have.  So this scores field has values ranging from
> 1.00-4.  There is also a count field.  I want to add a rank field such
> that all the records have a unique ranking, 1 through the number of
> records (thousands).  The rank is based on the score first, the count
> second.  So, a record with a score of 4 and a count of 385 is ranked
> higher than a record with a score of 4 and a count of 213 AND higher
> than record with a score of 3.25 with a count of 4640.
>
> My thought was to add the unique score values to a list and loop thru
> the list... sort records with score=listItem, add ranking... not quite
> sure how to do this!

things = getListOfYourThings()
things.sort(reverse=True, key=lambda item: (item.score, item.count))
for i, thing in enumerate(things):
thing.rank = i + 1

Cheers,
Chris
--
http://rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Run time default arguments

2011-08-25 Thread ting
On Aug 25, 10:35 am, Arnaud Delobelle  wrote:
> You're close to the usual idiom:
>
> def doSomething(debug=None):
>     if debug is None:
>         debug = defaults['debug']
>     ...
>
> Note the use of 'is' rather than '=='
> HTH

Hmm, from what you are saying, it seems like there's no elegant way to
handle run time defaults for function arguments, meaning that I should
probably write a sql-esc coalesce function to keep my code cleaner. I
take it that most people who run into this situation do this?

def coalesce(*args):
  for a in args:
if a is not None:
  return a
  return None

def doSomething(debug=None):
  debug = coalesce(debug,defaults['debug'])
  # blah blah blah
--
// T.Hsu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Run time default arguments

2011-08-25 Thread Chris Angelico
On Fri, Aug 26, 2011 at 6:54 AM,   wrote:
> def doSomething(debug=None):
>  debug = coalesce(debug,defaults['debug'])
>  # blah blah blah
>

It won't work with a True/False flag, but if you can guarantee that
all real options will evaluate as True, you can use a simpler
notation:

def doSomething(option=None):
  option=option or defaults['option']

You can't explicitly set option to False/0 with this, but it is a bit
cleaner (IMO - some may disagree).

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Design principles: no bool arguments

2011-08-25 Thread Ian Kelly
On Thu, Aug 25, 2011 at 3:29 AM, Thomas 'PointedEars' Lahn
 wrote:
> Both variants work (even in Py3) if you only define
>
> class Data(object):
>  def merge_with(self, bar, overwrite_duplicates):
>    pass
>
> data1 = Data()
> data2 = Data()
>
> You have to define
>
> class Data(object):
>  def merge_with(self, bar, **kwargs):
>    # do something with kwargs['overwrite_duplicates']
>    pass
>
> data1 = Data()
> data2 = Data()
>
> so that
>
> data1.merge_with(data2, True);
>
> is a syntax error ("TypeError: merge_with() takes exactly 2 arguments (3
> given)").
>
> IOW, this advantage of Python in readability is not only caused by API
> definition, but also by how the API is used.  It might turn into a
> disadvantage if key lookups make the code expensive memory- and runtime
> wise.
>
> And you will still have to know the underlying signature to name the
> argument.  Worse, with keyword arguments you *have to* look up the
> documentation (i. e., it needs to be well-documented as well) to know its
> name (as the compiler can only tell you "kwargs").

Note though that Python 3 adds actual keyword-only arguments, which
address all of your points:

class Data:
def merge_with(self, bar, *, overwrite_duplicates):
pass

>>> data1.merge_with(data2, True)
TypeError: merge_with() takes exactly 2 positional arguments (3 given)
>>> data1.merge_with(data2)
TypeError: merge_with() needs keyword-only argument overwrite_duplicates
>>> data1.merge_with(data2, overwrite_duplicates=True)
>>>

Of course, in Python 2 that definition would be a syntax error, so you
can't really take advantage of it if you need compatibility.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT-ish] Design principles: no bool arguments

2011-08-25 Thread Roy Smith
In article <4e55f604$0$29973$c3e8da3$54964...@news.astraweb.com>,
 Steven D'Aprano  wrote:

> [1] This is the Internet. There's *always* a certain amount of disagreement.

No there's not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Learning python reading software source code

2011-08-25 Thread Chetan Harjani
Hello friends,

I have learned the basic syntax of python through the book HOW TO THINK LIKE
A COMPUTER SCIENTIST n by reading first 10-11 chapters of Apress-BEGINNING
PROGRAMMING FROM NOVICE TO PROFESSIONAL.
(btw it was really very boring)

I am looking forward to learn further by understanding source code of
applications built in python. I guess i will begin with reading the source
code of MIRO http://www.getmiro.com/ .

So I am looking for suggestions on how one can understand the code better.
Any specific references I should look in as I stumble upon libraries n
functions while reading or just the python official docs would be enough?

thanking you
-- 
Chetan H Harjani
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning python reading software source code

2011-08-25 Thread Michael Hunter
On Thu, Aug 25, 2011 at 8:31 PM, Chetan Harjani
 wrote:
[read book, picked miro to read through]
> So I am looking for suggestions on how one can understand the code better.
> Any specific references I should look in as I stumble upon libraries n
> functions while reading or just the python official docs would be enough?

Mess the code up.  Make changes to it.  Alternate between writing
code, often reading code, and occasionally reading books.  The act of
having to mod the code and debug those modifications will lead you
through many documents.  But the documents on their own shouldn't usu.
be your guide.

A note on reading books.  A book or two can be useful for learning a
language.  But beyond that books about specific language have quickly
diminishing returns.  Instead read books about high order concepts
(e.g. software engineering, algorithms, problem domain specifics).

   Michael
-- 
http://mail.python.org/mailman/listinfo/python-list


How cai i encode url

2011-08-25 Thread John Smithury
Hi pythons.

following is my code

# -*- coding: utf8 -*-
import urllib2
import urllib

url = "http://a.shanting.mobi/百家讲坛/大国医/list";
print url
p1=u"百家讲坛".encode('utf8')
p2=u"大国医".encode('utf8')
encodeurl = "http://a.shanting.mobi/"+p1+"/"+p2+"/"+"list";
print encodeurl
mp3file = urllib2.urlopen(encodeurl)
output = open("list1", "wb")
output.write(mp3file.read())
output.close

---
but error following, why? what can i encode the url?

Traceback (most recent call last):
  File "D:/readurl.py", line 11, in 
mp3file = urllib2.urlopen(encodeurl)
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 398, in open
response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 511, in http_response
'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 436, in error
return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 370, in _call_chain
result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 519, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 404: Not Found
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any principle when writing python function

2011-08-25 Thread ting
On Aug 23, 7:59 am, smith jack  wrote:
> i have heard that function invocation in python is expensive, but make
> lots of functions are a good design habit in many other languages, so
> is there any principle when writing python function?
> for example, how many lines should form a function?

My suggestion is to think how you would test the function, in order to
get 100% code coverage. The parts of the function that are difficult
to test, those are the parts that you want to pull out into their own
separate function.

For example, a block of code within a conditional statement, where the
test condition cannot be passed in, is a prime example of a block of
code that should be pulled out into a separate function.

Obviously, there are times where this is not practical - exception
handling comes to mind - but that should be your rule of thumb. If a
block of code is hard to test, pull it out into it's own function, so
that it's easier to test.
--
// T.Hsu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How cai i encode url

2011-08-25 Thread Peter Otten
John Smithury wrote:

> Hi pythons.
> 
> following is my code
> 
> # -*- coding: utf8 -*-
> import urllib2
> import urllib
> 
> url = "http://a.shanting.mobi/百家讲坛/大国医/list";
> print url
> p1=u"百家讲坛".encode('utf8')
> p2=u"大国医".encode('utf8')
> encodeurl = "http://a.shanting.mobi/"+p1+"/"+p2+"/"+"list";
> print encodeurl
> mp3file = urllib2.urlopen(encodeurl)
> output = open("list1", "wb")
> output.write(mp3file.read())
> output.close
> 
> ---
> but error following, why? what can i encode the url?

The following seems to work:

# -*- coding: utf-8 -*-
import urllib2

url = u"http://a.shanting.mobi/百家讲坛/大国医/list";
encoded_url = urllib2.quote(url.encode("utf-8"), safe=":/")
instream = urllib2.urlopen(encoded_url)
with open("list1", "wb") as outstream:
outstream.write(instream.read())


-- 
http://mail.python.org/mailman/listinfo/python-list