Re: Idiosyncratic python

2015-09-24 Thread jmp

On 09/24/2015 08:02 AM, Steven D'Aprano wrote:

I was looking at an in-house code base today, and the author seems to have a
rather idiosyncratic approach to Python. For example:


for k, v in mydict.items():
 del(k)
 ...


instead of the more obvious

for v in mydict.values():
 ...



What are your favorite not-wrong-just-weird Python moments?


A lot of our in base weird python comes from heavily C-wired people:

The classic
for i in range(len(alist)):
  print alist[i]

with its twin brother

i=0
while i < len(alist):
  print alist[i]
  i += 1

And the even more annoying

result = Result()
getResult(result)

JM




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


Re: PyInstaller+ Python3.5 (h5py import error)

2015-09-24 Thread Heli Nix
Thanks Christian, 

It turned out that h5py.defs was not the only hidden import that I needed to 
add. 

I managed to get it working with the follwoing command adding 4 hidden imports. 


pyinstaller --hidden-import=h5py.defs --hidden-import=h5py.utils  
--hidden-import=h5py.h5ac --hidden-import=h5py._proxy  test.py


is there anyway that you can use to add all h5py submodules all together?

Thanks, 



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


Re: ConnectionError handling problem

2015-09-24 Thread Laura Creighton
In a message of Wed, 23 Sep 2015 19:49:17 -0700, shiva upreti writes:
>Hi
>If my script hangs because of the reasons you mentioned above, why doesnt it 
>catch ConnectionError?
>My script stops for a while and when I press CTRL+C, it shows ConnectionError 
>without terminating the process, and the script resumes from where it left off.

This is exactly what you asked it to do. :)

>>  try:
>>  r=requests.post(url, data=query_args)
>>  except:
>>  print "Connection error"
>>  time.sleep(30)
>>  continue

try to do something until you get an Exception.  Since that is a
naked except, absolutely any Exception will do.  That you
print out 'Connection error' doesn't mean that you are only
catching exceptions raised by trying to send something to the
other end ... any Exception will do.

So what happens when you press Control-C?

You get a KeyboardInterrupt exception! :)

see: https://docs.python.org/2/library/exceptions.html

And  you are catching it :)
And when you catch it you print  Connection error and keep on
trying.

This is why people were telling you that naked try:except: pairs,
are rarely what you want.  You didn't want to catch control-c but
you caught it anyway.

Laura

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


Re: PyInstaller+ Python3.5 (h5py import error)

2015-09-24 Thread Laura Creighton
In a message of Thu, 24 Sep 2015 02:58:35 -0700, Heli Nix writes:
>Thanks Christian, 
>
>It turned out that h5py.defs was not the only hidden import that I needed to 
>add. 
>
>I managed to get it working with the follwoing command adding 4 hidden 
>imports. 
>
>
>pyinstaller --hidden-import=h5py.defs --hidden-import=h5py.utils  
>--hidden-import=h5py.h5ac --hidden-import=h5py._proxy  test.py
>
>
>is there anyway that you can use to add all h5py submodules all together?
>
>Thanks, 
>

Yes.  You can use a hook file.
see: https://pythonhosted.org/PyInstaller/#using-hook-files

Laura

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


Re: Idiosyncratic python

2015-09-24 Thread paul.hermeneutic
> A lot of our in base weird python comes from heavily C-wired people:
>
> The classic
> for i in range(len(alist)):
>   print alist[i]
>
> with its twin brother
>
> i=0
> while i < len(alist):
>   print alist[i]
>   i += 1
>
> And the even more annoying
>
> result = Result()
> getResult(result)
>
> JM

Please follow up with good ways to write these. I hear that creating one
really good way is a Python maxim.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Idiosyncratic python

2015-09-24 Thread Mark Lawrence

On 24/09/2015 13:50, paul.hermeneu...@gmail.com wrote:

 > A lot of our in base weird python comes from heavily C-wired people:
 >
 > The classic
 > for i in range(len(alist)):
 >   print alist[i]
 >
 > with its twin brother
 >
 > i=0
 > while i < len(alist):
 >   print alist[i]
 >   i += 1
 >
 > And the even more annoying
 >
 > result = Result()
 > getResult(result)
 >
 > JM

Please follow up with good ways to write these. I hear that creating one
really good way is a Python maxim.



for item in alist:
print(item)

If you *think* you need the index:-

for i, item in enumerate(alist):
print(i, item)
`i` defaults to 0, but there is a `start` keyword argument that lets you 
set it to anything you like.


Better IMHO is to see what the itertools module[1] offers, either 
directly or through recipes.  The latter are available on pypi as 
more-itertools[2].


[1] https://docs.python.org/3/library/itertools.html
[2] https://pypi.python.org/pypi/more-itertools/

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: Sending a python argument to a Boost.Python function

2015-09-24 Thread Laura Creighton
Try that question here:
https://mail.python.org/mailman/listinfo/cplusplus-sig

Laura
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python, convert an integer into an index?

2015-09-24 Thread Anssi Saari
Dennis Lee Bieber  writes:

> On Wed, 23 Sep 2015 00:21:22 +0200, Laura Creighton 
> declaimed the following:
>
>
>>
>>You need to convert your results into a string first.
>>
>>result_int=1234523
>>result_list=[]
>>
>>for digit in str(result_int):   
>>result_list.append(int(digit))
>>
>
>   Rather wordy... 
>
 [int(i) for i in str(1234523)]
> [1, 2, 3, 4, 5, 2, 3]

I'm suprised. Why not just:

list(str(results))

In other words, is there something else the list constructor should do
with a string other than convert it to a list?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python, convert an integer into an index?

2015-09-24 Thread MRAB

On 2015-09-23 10:01, Anssi Saari wrote:

Dennis Lee Bieber  writes:


On Wed, 23 Sep 2015 00:21:22 +0200, Laura Creighton 
declaimed the following:




You need to convert your results into a string first.

result_int=1234523
result_list=[]

for digit in str(result_int):
   result_list.append(int(digit))



Rather wordy... 


[int(i) for i in str(1234523)]

[1, 2, 3, 4, 5, 2, 3]


I'm suprised. Why not just:

list(str(results))

In other words, is there something else the list constructor should do
with a string other than convert it to a list?


The OP wanted the result to be a list of ints, not a list of strings.

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


Re: Python, convert an integer into an index?

2015-09-24 Thread paul.hermeneutic
>> I'm suprised. Why not just:
>>
>> list(str(results))
>>
>> In other words, is there something else the list constructor should do
>> with a string other than convert it to a list?
>>
> The OP wanted the result to be a list of ints, not a list of strings.

[int(x) for x in list(str(results))]
-- 
https://mail.python.org/mailman/listinfo/python-list


querying hive database using python

2015-09-24 Thread heenameena1234
I have server A and Server B. Server B is a hadoop cluster which has hive 
database and etc..
Server A has python 2.7. I would like to write a hive query using python on 
Server A to pull data from Server B. Server A and B has connectivity and no 
issues with network etc..

I have installed all necessary python packages on Server A. I wrote a python 
code using hive_utils package but it seems this code doesn't throw error or 
pull data, just hangs there. Can you please take a look at it and let me know 
what is the issue with code or suggest if you have better way or package could 
be used to pull data with example code. Thank you for your help.

here is the code I wrote.
CODE: SELECT ALL
#!/usr/bin/env python
import hive_utils

query = """
SELECT *
FROM test
"""
hive_client = hive_utils.HiveClient(
server='10.25.36.75',
port=1,
db='camp'
)
a = hive_client.execute(query)
a = list(a)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Idiosyncratic python

2015-09-24 Thread jmp

On 09/24/2015 02:50 PM, paul.hermeneu...@gmail.com wrote:

 > A lot of our in base weird python comes from heavily C-wired people:
 >
 > The classic
 > for i in range(len(alist)):
 >   print alist[i]
 >
 > with its twin brother
 >
 > i=0
 > while i < len(alist):
 >   print alist[i]
 >   i += 1
 >
 > And the even more annoying
 >
 > result = Result()
 > getResult(result)
 >
 > JM

Please follow up with good ways to write these. I hear that creating one
really good way is a Python maxim.


for item in alist:
  print item

and

result = getResult()

For the later, the original weird form come from a C habit to allocate 
returned structures within the caller and provide a pointer to it so the 
function can fill the data in, otherwise the structure is lost as the 
stack is popped out and the structure content is garbage. None of this 
make any sense in python.


JM


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


Re: Python, convert an integer into an index?

2015-09-24 Thread jmp

On 09/24/2015 03:45 PM, paul.hermeneu...@gmail.com wrote:

 >> I'm suprised. Why not just:
 >>
 >> list(str(results))
 >>
 >> In other words, is there something else the list constructor should do
 >> with a string other than convert it to a list?
 >>
 > The OP wanted the result to be a list of ints, not a list of strings.

[int(x) for x in list(str(results))]


Side note : strings are already iterable, the list function is superfluous.


jm


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


Installing pywin32.

2015-09-24 Thread ashwath
Hi Sir/Madam
 
 
When I try to run my python program where I am using the pywin32 module I am 
getting the error as win32api module not found so how to install this module 
please let me know ASP.
 
Thank You
Ashwath B H
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Idiosyncratic python

2015-09-24 Thread Ian Kelly
On Thu, Sep 24, 2015 at 8:07 AM, jmp  wrote:
> result = getResult()
>
> For the later, the original weird form come from a C habit to allocate
> returned structures within the caller and provide a pointer to it so the
> function can fill the data in, otherwise the structure is lost as the stack
> is popped out and the structure content is garbage. None of this make any
> sense in python.

Only if the structure is allocated on the stack and returned by
pointer. If it's returned by value, then the content remains intact,
but at the expense of copying it. The other option of course would be
to allocate it on the heap and return the pointer, but this needlessly
incurs malloc overhead and creates an opportunity for a memory leak if
the variable is naturally stack-scoped. Python effectively takes this
option, as everything is allocated on the heap. Leaving it up to the
caller to provide a pointer also gives the caller the option of
allocating on the stack or the heap as best fits the context.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python, convert an integer into an index?

2015-09-24 Thread paul.hermeneutic
Good idea.

>>> [int(x) for x in str(results)]
[1, 2, 3]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Installing pywin32.

2015-09-24 Thread Zachary Ware
On Thu, Sep 24, 2015 at 8:58 AM,   wrote:
> Hi Sir/Madam
>
>
> When I try to run my python program where I am using the pywin32 module I am
> getting the error as win32api module not found so how to install this module
> please let me know ASP.

Have you already installed or tried to install pywin32?  What version
of Python are you running, where did you get it, and on which version
of Windows?  In the absence of further information, I'll give you the
quick and easy incantation for installing pywin32: `python -m pip
install pypiwin32`.  There are any number of ways that can fail
depending on your answers to my questions, though.

-- 
Zach
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Re: Installing pywin32.

2015-09-24 Thread Zachary Ware
Two notes about local etiquette:

1) Please reply to the list rather than to me directly.  I only
include your address in the cc: in case you aren't subscribed (which
you should be, unless you're reading via the newsgroup), since I don't
recognize you as a regular poster.  I'll soon stop doing so.
2) Please do not top-post.  Rather, add your reply directly beneath
the particular line you're replying to, as I do below.

On Thu, Sep 24, 2015 at 10:39 AM,   wrote:
> Hi
>
> I am pleased with your reply thanks for it.
> System environment is like this
>
> OS - windows 7 64 bit machine.
> Python - pywin3.5

Where did you get it from?  I don't know of any product named
"pywin3.5".  There's 'pywin32' (as in 'Python interface to Win32',
available from http://pywin32.sourceforge.net/) and Python 3.5 (as in
'CPython 3.5.0 for Windows', available from https://www.python.org/).

> even pip is not installed if I run pip its shows like pip command not found.

Installing pip is an option in the Python 3.5 (and 3.4, and 2.7.10)
installer.  If you didn't select it, it won't be installed.  You can
try running 'python -m ensurepip' to install pip after the main
installation of Python.

> From which path I have to run this python -m pip install pypiwin32

Doesn't matter; as long as the 'python' command can be found and that
Python has pip installed, this command will install pywin32 into the
global site-packages directory of that Python.

Also, I should have directed you to `py -m pip install pypiwin32` to
make use of the Python Launcher, which is always on PATH (if it was
installed, it's also an option in the installer).

-- 
Zach
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python, convert an integer into an index?

2015-09-24 Thread Lorenzo Sutton



On 23/09/2015 17:32, Denis McMahon wrote:

On Tue, 22 Sep 2015 14:43:55 -0700, Chris Roberts wrote:


results = 134523  #(Integer)


This appears to be an integer expressed (presumably) in base 10 with 6
digits


Desired:
results = [1, 2, 3, 4, 5, 2, 3]   #(INDEX)


This appears to be a python list of 7 elements, with the first and the
the third through seventh elements corresponding to the first and the
second through sixth most significant digits respectively of the
previously discussed integer.

I can't actually see any direct method of creating the list given from
the number given.

However, if I understand the intent of the question you meant to ask, you
might find that the following code does something interesting:

x = 9876543210
y = []

while x > 0:
 y.append(x % 10)
 x = int(x / 10)

y = list(reversed(y))
print y


I like the math approach even if the pythonic list string is quicker...

One 'math' way would also be (avoiding the list reverse, but need to 
import math):


>>> import math
>>> result = 1234567
>>> digits = int(math.log10(result) + 1)
>>> y = []
>>> for x in range(digits, 0, -1):
number = result % (10 ** x) / (10 **(x-1))
y.append(int(number))

>>> y
[1, 2, 3, 4, 5, 6, 7]
--
https://mail.python.org/mailman/listinfo/python-list


Re: Idiosyncratic python

2015-09-24 Thread Todd
Using list indexing with booleans in place of a ternary operator.

a = False
b = [var2, var1][a]

Instead of:

b = var1 if a else var2
On Sep 24, 2015 8:06 AM, "Steven D'Aprano" <
steve+comp.lang.pyt...@pearwood.info> wrote:

> I was looking at an in-house code base today, and the author seems to have
> a
> rather idiosyncratic approach to Python. For example:
>
>
> for k, v in mydict.items():
> del(k)
> ...
>
>
> instead of the more obvious
>
> for v in mydict.values():
> ...
>
>
>
> What are your favorite not-wrong-just-weird Python moments?
>
>
>
> --
> Steve
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Idiosyncratic python

2015-09-24 Thread Chris Angelico
On Fri, Sep 25, 2015 at 2:54 AM, Todd  wrote:
> Using list indexing with booleans in place of a ternary operator.
>
> a = False
> b = [var2, var1][a]
>
> Instead of:
>
> b = var1 if a else var2

Be careful - these are not semantically identical. The first one
evaluates both var1 and var2, while the second will evaluate only the
one it needs. This might be significant if they're not simple names.

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


Re: Idiosyncratic python

2015-09-24 Thread Laurent Pointal
wxjmfa...@gmail.com wrote:

> Le jeudi 24 septembre 2015 08:02:38 UTC+2, Steven D'Aprano a écrit :
>> 
>> 
>> What are your favorite not-wrong-just-weird Python moments?
>> 
>> 
> Showing how to make Python 3.5.0 crash by
> just using an "é", U+00E9.

Like this ?


Python 3.5.0 (default, Sep 24 2015, 19:47:57) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> s = "\u00E9"
>>> print(s)
é



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


Re: Idiosyncratic python

2015-09-24 Thread jmp

On 09/24/2015 04:26 PM, Ian Kelly wrote:

On Thu, Sep 24, 2015 at 8:07 AM, jmp  wrote:

result = getResult()

For the later, the original weird form come from a C habit to allocate
returned structures within the caller and provide a pointer to it so the
function can fill the data in, otherwise the structure is lost as the stack
is popped out and the structure content is garbage. None of this make any
sense in python.


Only if the structure is allocated on the stack and returned by
pointer. If it's returned by value, then the content remains intact,
but at the expense of copying it. The other option of course would be
to allocate it on the heap and return the pointer, but this needlessly
incurs malloc overhead and creates an opportunity for a memory leak if
the variable is naturally stack-scoped. Python effectively takes this
option, as everything is allocated on the heap. Leaving it up to the
caller to provide a pointer also gives the caller the option of
allocating on the stack or the heap as best fits the context.



I'm not an expert but I think this "return by value thing" is only for C++.
In vintage C, you can only return something that fits within a register.

Anyway, there's a lot of legit C code in which functions are plagued by 
'out parameters' and somehow it has transpired in some python code for 
no reason :o)


jm

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


Re: Idiosyncratic python

2015-09-24 Thread Ian Kelly
On Thu, Sep 24, 2015 at 12:04 PM, jmp  wrote:
> I'm not an expert but I think this "return by value thing" is only for C++.
> In vintage C, you can only return something that fits within a register.

If that was true at one time, it was before ANSI C.

$ cat test.c
#include 

struct foo {
  int a;
  long b;
  float c;
  double d;
};

struct foo get_foo() {
  struct foo value;
  value.a = 12;
  value.b = 92L;
  value.c = 4.5f;
  value.d = -21.5;
  return value;
}

int main() {
  struct foo value = get_foo();
  assert(value.a == 12);
  assert(value.b == 92L);
  assert(value.c == 4.5f);
  assert(value.d == -21.5);
  return 0;
}
$ gcc -Wall -O0 -std=c89 test.c
$ ./a.out
$

There is a danger however in that it's only a shallow copy. If any
struct members are pointers, then the pointer value will be copied,
not the thing pointed to.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Idiosyncratic python

2015-09-24 Thread Todd
On Sep 24, 2015 18:59, "Chris Angelico"  wrote:
>
> On Fri, Sep 25, 2015 at 2:54 AM, Todd  wrote:
> > Using list indexing with booleans in place of a ternary operator.
> >
> > a = False
> > b = [var2, var1][a]
> >
> > Instead of:
> >
> > b = var1 if a else var2
>
> Be careful - these are not semantically identical. The first one
> evaluates both var1 and var2, while the second will evaluate only the
> one it needs. This might be significant if they're not simple names.

True, but the code I saw doing this was just choosing between simple float
literals.
-- 
https://mail.python.org/mailman/listinfo/python-list


Learning Modules, Arguments, Parameters (imma noob)

2015-09-24 Thread codywcox
I seem to be having a problem understanding how arguments and parameters work, 
Most likely why my code will not run. 
Can anyone elaborate on what I am doing wrong?

'''
Cody Cox
9/16/2015
Programming Exercise 1 - Kilometer Converter
Design a modular program that asks the user to enter a distance in kilometers 
and then convert it to miles
Miles = Kilometers * 0.6214
'''

def main():
   get_input()
   convert_kilo()


 def get_input(kilo):
   kilo = float(input('Enter Kilometers: '))
   return kilo

 def convert_kilo(kilo,miles):
 miles = float(kilo * 0.6214)
 print( kilo,' kilometers converts to ',miles,' miles')

 main()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Learning Modules, Arguments, Parameters (imma noob)

2015-09-24 Thread Joel Goldstick
On Thu, Sep 24, 2015 at 2:45 PM,  wrote:

> I seem to be having a problem understanding how arguments and parameters
> work, Most likely why my code will not run.
> Can anyone elaborate on what I am doing wrong?
>
> '''
> Cody Cox
> 9/16/2015
> Programming Exercise 1 - Kilometer Converter
> Design a modular program that asks the user to enter a distance in
> kilometers and then convert it to miles
> Miles = Kilometers * 0.6214
> '''
>
> def main():
>get_input()
>

Change the above call to:
  kilos = get_input()
This is because your function returns that value


>convert_kilo()
>
This one you need to pass the kilos argument, and you don't need to pass
the miles parameter (see below)
   convert_kilo(kilos)

>
>
>  def get_input(kilo):
>
You defined get_input with no parameters, so it gets no arguments when you
call it:
def get_input():

>kilo = float(input('Enter Kilometers: '))
>return kilo
>
>  def convert_kilo(kilo,miles):
>
Make the above:
def convert_kilo(kilo):

>  miles = float(kilo * 0.6214)
>  print( kilo,' kilometers converts to ',miles,' miles')
>
>  main()
>

When you define a function, the names between the parentheses are called
parameters.  When you call the function, they are called arguments.  They
need to match.  When you return a value from a function, you need to put a
name to it, or it is lost.

> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Learning Modules, Arguments, Parameters (imma noob)

2015-09-24 Thread MRAB

On 2015-09-24 19:45, codyw...@gmail.com wrote:

I seem to be having a problem understanding how arguments and parameters work, 
Most likely why my code will not run.
Can anyone elaborate on what I am doing wrong?

'''
Cody Cox
9/16/2015
Programming Exercise 1 - Kilometer Converter
Design a modular program that asks the user to enter a distance in kilometers 
and then convert it to miles
Miles = Kilometers * 0.6214
'''


First of all, it looks like your indentation is slightly off because
"def main" line is that the left margin and the other 2 "def" lines and
the "main()" line aren't.


def main():


You're not passing anything into 'get_input', neither are you saving
any result that it might be returning.


get_input()


You're not passing anything into 'convert_kilo'.


convert_kilo()



You're defining 'get_input' to accept 1 parameter 'kilo'. Why? You're
assigning to 'kilo' in the first line, so any value you _did_ pass in
would be ignored.


  def get_input(kilo):
kilo = float(input('Enter Kilometers: '))
return kilo


You're defining 'convert_kilo' to accept 2 parameters. You're using the
'kilo' parameter, but not the 'miles' parameter because you're
assigning to it on the first line, so any value you _did_ pass in would
be ignored.


  def convert_kilo(kilo,miles):


'kilo' is already a float, and you're multiplying it by a float, so the
'float' call is pointless.


  miles = float(kilo * 0.6214)
  print( kilo,' kilometers converts to ',miles,' miles')

  main()



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


Re: Learning Modules, Arguments, Parameters (imma noob)

2015-09-24 Thread John Gordon
In <7ad8941d-04aa-42c5-82e9-10cdf02ab...@googlegroups.com> codyw...@gmail.com 
writes:

> I seem to be having a problem understanding how arguments and parameters
> work, Most likely why my code will not run. Can anyone elaborate on what
> I am doing wrong?

>  def get_input(kilo):
>kilo = float(input('Enter Kilometers: '))
>return kilo

get_input() gets all its input from the keyboard.  It doesn't need any
arguments.

>  def convert_kilo(kilo,miles):
>  miles = float(kilo * 0.6214)
>  print( kilo,' kilometers converts to ',miles,' miles')

convert_kilo() calculates miles on its own, so you don't need to pass it
as an argument.

> def main():
>get_input()
>convert_kilo()
>
>  main()

When calling get_input, you need to save the return value in a variable,
and then pass that variable as an argument to convert_kilo.

The updated code would look like this:

def main():
kilo = get_input()
convert_kilo(kilo)

def get_input():
kilo = float(input('Enter Kilometers: '))
return kilo

def convert_kilo(kilo):
miles = float(kilo * 0.6214)
print( kilo,' kilometers converts to ',miles,' miles')

main()

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


Re: Idiosyncratic python

2015-09-24 Thread Mark Lawrence

On 24/09/2015 18:50, Laurent Pointal wrote:

wxjmfa...@gmail.com wrote:


Le jeudi 24 septembre 2015 08:02:38 UTC+2, Steven D'Aprano a écrit :



What are your favorite not-wrong-just-weird Python moments?



Showing how to make Python 3.5.0 crash by
just using an "é", U+00E9.


Would you like to show us all how, or do you think you'd be far too 
embarassed by once again showing that you haven't got the faintest idea 
what you're talking about?




Like this ?


Python 3.5.0 (default, Sep 24 2015, 19:47:57)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.

s = "\u00E9"
print(s)

é



Your test must be wrong as the RUE knows everything.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Modifying signature of ctor in class

2015-09-24 Thread Joseph L. Casale
I have a class factory where I dynamically add a constructor to the class 
output.
The method is a closure and works just fine, however to accommodate the varied
input its signature is (*args, **kwargs).

While I modify the doc strings, the ctor sig is not optimal. Without building
this a string and using eval, is there anything that can be done about this?

Thanks,
jlc
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Learning Modules, Arguments, Parameters (imma noob)

2015-09-24 Thread Larry Hudson via Python-list

On 09/24/2015 11:45 AM, codyw...@gmail.com wrote:

I seem to be having a problem understanding how arguments and parameters work, 
Most likely why my code will not run.
Can anyone elaborate on what I am doing wrong?

'''
Cody Cox
9/16/2015
Programming Exercise 1 - Kilometer Converter
Design a modular program that asks the user to enter a distance in kilometers 
and then convert it to miles
Miles = Kilometers * 0.6214
'''

def main():
get_input()
convert_kilo()


  def get_input(kilo):
kilo = float(input('Enter Kilometers: '))
return kilo

  def convert_kilo(kilo,miles):
  miles = float(kilo * 0.6214)
  print( kilo,' kilometers converts to ',miles,' miles')

  main()


--
> def main():
>...
I'm going to discribe this last

>   def get_input(kilo):
> kilo = float(input('Enter Kilometers: '))
> return kilo
>
1)  def get_input(kilo):  has a leading space.  This is an indenting error
2)  You use parameters to send data TO the function, NOT to return it (generally, there are 
exceptions).  Leave out the kilo, you want simply 'def get_input():'

3)  The body,  kilo = ... and return ..., is ok, but can be shortened to a 
single line:
return float(input('Enter Kilometers: '))

>   def convert_kilo(kilo,miles):
>   miles = float(kilo * 0.6214)
>   print( kilo,' kilometers converts to ',miles,' miles')
>
1)  Again indenting error, and miles (an output) is not needed as a parameter.
2)  miles = float(kilo * 0.6214):  kilo and 0.6214 are already floats.  There is no need to 
_convert_ to float.  Doesn't hurt, but it is redundant.
3)  The print is acceptable, but has unnecessary spaces.  Print() by default puts a space 
between the items, so using spaces inside the strings gives you double-spaces, one from the 
print() and one from the string.


> def main():
> get_input()
> convert_kilo()
>
1)  get_input() as you have it written requires a parameter, you are not giving it one. 
However, as I explained above, get_input() should not have a parameter anyway.

2)  get_imput() returns a value (kilo), but here you are throwing it away.  
This needs to be:
kilo = get_input()
3)  convert_kilo() _requires_ a parameter, you are not giving one.  And it does NOT need the 
second (miles) parameter that you originally wrote.  What you want is:

   convert_kilo(kilo)

I hope you can make sense out of my explanations.

 -=- Larry -=-

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


Re: Idiosyncratic python

2015-09-24 Thread Ned Batchelder
On Thursday, September 24, 2015 at 2:02:38 AM UTC-4, Steven D'Aprano wrote:
> What are your favorite not-wrong-just-weird Python moments?

I've seen this a number of times:

dict_of_values.update({'key': some_value})

why not:

dict_of_values['key'] = some_value

I've considered writing a Pylint plugin to flag these...

--Ned.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Idiosyncratic python

2015-09-24 Thread Laura Creighton
In a message of Thu, 24 Sep 2015 13:46:27 -0700, Ned Batchelder writes:
>On Thursday, September 24, 2015 at 2:02:38 AM UTC-4, Steven D'Aprano wrote:
>> What are your favorite not-wrong-just-weird Python moments?
>
>I've seen this a number of times:
>
>dict_of_values.update({'key': some_value})
>
>why not:
>
>dict_of_values['key'] = some_value
>
>I've considered writing a Pylint plugin to flag these...
>
>--Ned.

A student today had a similar version of this one:

Every time he wanted to change the value of dictionary mapping he would
write:
w={'key': new_value}
dict_of_values.update(w)

Laura

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


Re: Modifying signature of ctor in class

2015-09-24 Thread Chris Angelico
On Fri, Sep 25, 2015 at 6:28 AM, Joseph L. Casale
 wrote:
> I have a class factory where I dynamically add a constructor to the class 
> output.
> The method is a closure and works just fine, however to accommodate the varied
> input its signature is (*args, **kwargs).
>
> While I modify the doc strings, the ctor sig is not optimal. Without building
> this a string and using eval, is there anything that can be done about this?
>

I don't think you can easily change the function's own definition,
other than by using eval (or equivalent shenanigans, like crafting
your own bytecode); but as of Python 3.something, the help() function
looks for a __wrapped__ attribute and will take function args from
that instead of the function itself. That way, when you use
functools.wraps(), it copies in the docstring and stuff, and as far as
help() is concerned, copies in the argument list too.

No idea whether you'll be able to do that too, but it's a fairly
effective way to get around the problem if you can.

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


Re: Modifying signature of ctor in class

2015-09-24 Thread Joseph L. Casale
> You can use the FunctionType class found in the types module (and its 
> friends) to create functions on the run.
> And you can use the 'inspect' module to inspect existing functions, if you 
> need to base the new function on an existing one.

Hi Gal,
Seems the types module docs do not even have a single line of docs
for FunctionType and there isn't any that I found online. From the few
examples on StackOverflow it appears like it might do the job however
I do not see how to specify a signature, I only see how to specify defaults.

Do you have any ideas?

Thanks for the info,
jlc
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Modifying signature of ctor in class

2015-09-24 Thread Joseph L. Casale
> I don't think you can easily change the function's own definition,
> other than by using eval (or equivalent shenanigans, like crafting
> your own bytecode); but as of Python 3.something, the help() function
> looks for a __wrapped__ attribute and will take function args from
> that instead of the function itself. That way, when you use
> functools.wraps(), it copies in the docstring and stuff, and as far as
> help() is concerned, copies in the argument list too.
> 
> No idea whether you'll be able to do that too, but it's a fairly
> effective way to get around the problem if you can.

Hi Chris,
That is helpful. It still leaves me with generating a string function
and eval'ing or compiling it to swipe the sig. At the point I could
rebuild the entire function and simply apply it.

Where all but a valid sig helps is for introspection such as tab completing
with ipython or using an IDE etc.

Thanks everyone,
jlc
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Idiosyncratic python

2015-09-24 Thread Chris Angelico
On Fri, Sep 25, 2015 at 7:08 AM, Laura Creighton  wrote:
> In a message of Thu, 24 Sep 2015 13:46:27 -0700, Ned Batchelder writes:
>>On Thursday, September 24, 2015 at 2:02:38 AM UTC-4, Steven D'Aprano wrote:
>>> What are your favorite not-wrong-just-weird Python moments?
>>
>>I've seen this a number of times:
>>
>>dict_of_values.update({'key': some_value})
>>
>>why not:
>>
>>dict_of_values['key'] = some_value
>>
>>I've considered writing a Pylint plugin to flag these...
>>
>>--Ned.
>
> A student today had a similar version of this one:
>
> Every time he wanted to change the value of dictionary mapping he would
> write:
> w={'key': new_value}
> dict_of_values.update(w)

That's a new one on me! The oddest dictionary code any of my students
has come out with (so far!) was a slavish habit of always iterating
over them thus:

for k,v in some_dict.items():

where some_dict is the only part that changed. So everywhere through
the code - even in nested loops - all dictionary iteration used "k"
and "v".

But I suspect it's exactly the same. Saw some code somewhere, found
that it worked, used it. If you don't understand something, don't
change it... which is a good policy in general, I suppose :)

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


Re: Modifying signature of ctor in class

2015-09-24 Thread Chris Angelico
On Fri, Sep 25, 2015 at 7:45 AM, Joseph L. Casale
 wrote:
>> I don't think you can easily change the function's own definition,
>> other than by using eval (or equivalent shenanigans, like crafting
>> your own bytecode); but as of Python 3.something, the help() function
>> looks for a __wrapped__ attribute and will take function args from
>> that instead of the function itself. That way, when you use
>> functools.wraps(), it copies in the docstring and stuff, and as far as
>> help() is concerned, copies in the argument list too.
>>
>> No idea whether you'll be able to do that too, but it's a fairly
>> effective way to get around the problem if you can.
>
> Hi Chris,
> That is helpful. It still leaves me with generating a string function
> and eval'ing or compiling it to swipe the sig. At the point I could
> rebuild the entire function and simply apply it.
>
> Where all but a valid sig helps is for introspection such as tab completing
> with ipython or using an IDE etc.

I've no idea what your tab completion tools are going to be looking
at, so you'd have to dig into that and find out. This trick may or may
not work, but if it does, it'd mean you could possibly come up with
something that pretends to be a function (for introspection purposes),
without actually being one. That would let you construct a class that
ducktypes as a function and can return whatever it likes from
inspect.signature().

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


Re: Modifying signature of ctor in class

2015-09-24 Thread Ian Kelly
On Thu, Sep 24, 2015 at 2:28 PM, Joseph L. Casale
 wrote:
> I have a class factory where I dynamically add a constructor to the class 
> output.
> The method is a closure and works just fine, however to accommodate the varied
> input its signature is (*args, **kwargs).
>
> While I modify the doc strings, the ctor sig is not optimal. Without building
> this a string and using eval, is there anything that can be done about this?

In Python 3.3+ you can attach a Signature object to a function by
setting the function's __signature__ attribute. In Python 3.4+ the
__signature__ is used in generating the signature for PyDoc and
help().
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Modifying signature of ctor in class

2015-09-24 Thread Ian Kelly
On Thu, Sep 24, 2015 at 4:10 PM, Ian Kelly  wrote:
> On Thu, Sep 24, 2015 at 2:28 PM, Joseph L. Casale
>  wrote:
>> I have a class factory where I dynamically add a constructor to the class 
>> output.
>> The method is a closure and works just fine, however to accommodate the 
>> varied
>> input its signature is (*args, **kwargs).
>>
>> While I modify the doc strings, the ctor sig is not optimal. Without building
>> this a string and using eval, is there anything that can be done about this?
>
> In Python 3.3+ you can attach a Signature object to a function by
> setting the function's __signature__ attribute. In Python 3.4+ the
> __signature__ is used in generating the signature for PyDoc and
> help().

Quick and dirty example:

py> from inspect import Signature, Parameter
py> def foo(*args, **kwargs): pass
...
py> foo.__signature__ = Signature([Parameter('x',
Parameter.POSITIONAL_OR_KEYWORD), Parameter('y',
Parameter.KEYWORD_ONLY)])
py> help(foo)
Help on function foo in module __main__:

foo(x, *, y)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Modifying signature of ctor in class

2015-09-24 Thread Chris Angelico
On Fri, Sep 25, 2015 at 8:19 AM, Ian Kelly  wrote:
> Quick and dirty example:
>
> py> from inspect import Signature, Parameter
> py> def foo(*args, **kwargs): pass
> ...
> py> foo.__signature__ = Signature([Parameter('x',
> Parameter.POSITIONAL_OR_KEYWORD), Parameter('y',
> Parameter.KEYWORD_ONLY)])
> py> help(foo)
> Help on function foo in module __main__:
>
> foo(x, *, y)

Okay, that's a LOT easier than the stuff I was playing around with :)

Of course, it still requires that inspect.signature be used.

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


Re: Idiosyncratic python

2015-09-24 Thread sohcahtoa82
On Wednesday, September 23, 2015 at 11:02:38 PM UTC-7, Steven D'Aprano wrote:
> I was looking at an in-house code base today, and the author seems to have a 
> rather idiosyncratic approach to Python. For example:
> 
> 
> for k, v in mydict.items(): 
> del(k)
> ...
> 
> 
> instead of the more obvious
> 
> for v in mydict.values(): 
> ...
> 
> 
> 
> What are your favorite not-wrong-just-weird Python moments?
> 
> 
> 
> -- 
> Steve

I used to work with a guy that would put the verb at the END of a function 
name, rather than the beginning.  For example, rather then 
"GetSupportedVersion", he'd use "SupportedVersionGet".  Of course, I know 
plenty of people here will say it should be "get_supported_version", but that's 
another discussion entirely.

Another guy would frequently use "Grab" instead of "Get".  The fact that he 
used a different verb than the common convention though wasn't NEARLY as 
infuriating as the fact that he was inconsistent about it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Modifying signature of ctor in class

2015-09-24 Thread Joseph L. Casale
> py> from inspect import Signature, Parameter
> py> def foo(*args, **kwargs): pass
> ...
> py> foo.__signature__ = Signature([Parameter('x',
> Parameter.POSITIONAL_OR_KEYWORD), Parameter('y',
> Parameter.KEYWORD_ONLY)])
> py> help(foo)
> Help on function foo in module __main__:
> 
> foo(x, *, y)

That actually should harmlessly support Python versions less than 3.3
while simply accomplishing nothing. I don't even need a test for the version.

I'll go with that as a decent trade off.

Thanks!
jlc
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Modifying signature of ctor in class

2015-09-24 Thread Ian Kelly
On Thu, Sep 24, 2015 at 5:01 PM, Joseph L. Casale
 wrote:
>> py> from inspect import Signature, Parameter
>> py> def foo(*args, **kwargs): pass
>> ...
>> py> foo.__signature__ = Signature([Parameter('x',
>> Parameter.POSITIONAL_OR_KEYWORD), Parameter('y',
>> Parameter.KEYWORD_ONLY)])
>> py> help(foo)
>> Help on function foo in module __main__:
>>
>> foo(x, *, y)
>
> That actually should harmlessly support Python versions less than 3.3
> while simply accomplishing nothing. I don't even need a test for the version.
>
> I'll go with that as a decent trade off.

Well, setting the __signature__ attribute is harmless, but do note
that inspect.Signature doesn't exist before 3.3.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Idiosyncratic python

2015-09-24 Thread Mark Lawrence

On 24/09/2015 07:02, Steven D'Aprano wrote:

I was looking at an in-house code base today, and the author seems to have a
rather idiosyncratic approach to Python. For example:

for k, v in mydict.items():
 del(k)
 ...

instead of the more obvious

for v in mydict.values():
 ...

What are your favorite not-wrong-just-weird Python moments?



My favourite was from a guy I worked with years ago.  In C but I'm sure 
you'll enjoy it.  In all functions, something like:-


int flag = 0;
if flag {
printf("\nthe string");
}
else{
printf("the string");
flag = 1;
}

At least I think I've got it correct, too lazy to check, sorry :)

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: Idiosyncratic python

2015-09-24 Thread Akira Li
Mark Lawrence  writes:

> On 24/09/2015 07:02, Steven D'Aprano wrote:
>> I was looking at an in-house code base today, and the author seems to have a
>> rather idiosyncratic approach to Python. For example:
>>
>> for k, v in mydict.items():
>>  del(k)
>>  ...
>>
>> instead of the more obvious
>>
>> for v in mydict.values():
>>  ...
>>
>> What are your favorite not-wrong-just-weird Python moments?
>>
>
> My favourite was from a guy I worked with years ago.  In C but I'm
> sure you'll enjoy it.  In all functions, something like:-
>
> int flag = 0;
> if flag {
> printf("\nthe string");
> }
> else{
> printf("the string");
> flag = 1;
> }
>
> At least I think I've got it correct, too lazy to check, sorry :)

It looks like a sys.stdout.softspace hack in Python 2:

  print line, # comma!

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


Re: Idiosyncratic python

2015-09-24 Thread Steven D'Aprano
On Fri, 25 Sep 2015 02:54 am, Todd wrote:

> Using list indexing with booleans in place of a ternary operator.
> 
> a = False
> b = [var2, var1][a]
> 
> Instead of:
> 
> b = var1 if a else var2

Ah, you youngsters...  :-)

Using a bool to index into a list used to be the standard idiom, before the
ternary if was added to the language. So I don't consider it "weird",
especially as a lot of my code still supports Python 2.4 which doesn't
include the ternary if.

Sometimes, instead of a list, I'll use a dict:

{True: value1, False: value2}[flag]

to emulate ternary if.



-- 
Steven

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


Re: ConnectionError handling problem

2015-09-24 Thread Cameron Simpson

On 24Sep2015 12:38, Laura Creighton  wrote:

In a message of Wed, 23 Sep 2015 19:49:17 -0700, shiva upreti writes:
If my script hangs because of the reasons you mentioned above, why doesnt it 
catch ConnectionError?

My script stops for a while and when I press CTRL+C, it shows ConnectionError 
without terminating the process, and the script resumes from where it left off.


This is exactly what you asked it to do. :)


try:
r=requests.post(url, data=query_args)
except:
print "Connection error"
time.sleep(30)
continue


try to do something until you get an Exception.  Since that is a
naked except, absolutely any Exception will do.  That you
print out 'Connection error' doesn't mean that you are only
catching exceptions raised by trying to send something to the
other end ... any Exception will do.

[... snip ...]

Since nobody has offered this advice, let me:

Firstly, as already remarked bare excepts are overkill - they catch all sorts 
of things you shouldn't be handling.


That said, if you _don't know_ what exceptions are going to boils out of new 
code, this is one way to see them all. However, you are catching _everything_ 
but _not_ finding out what happened.


Try this:

   try:
   r=requests.post(url, data=query_args)
   except Exception as e:
   print "Exception:", e

That will at least _tell_ you what happened. You code is blithely presuming 
Connection Error and telling you that, but it is usually a lie.


Once you have characterised what exceptions you get, and which particular ones 
to handle, then modify your code to catch _only_ those and perform the specific 
suitable actions, and let the rest escape.


Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Re: Idiosyncratic python

2015-09-24 Thread Steven D'Aprano
On Fri, 25 Sep 2015 06:46 am, Ned Batchelder wrote:

> On Thursday, September 24, 2015 at 2:02:38 AM UTC-4, Steven D'Aprano
> wrote:
>> What are your favorite not-wrong-just-weird Python moments?
> 
> I've seen this a number of times:
> 
> dict_of_values.update({'key': some_value})
> 
> why not:
> 
> dict_of_values['key'] = some_value
> 
> I've considered writing a Pylint plugin to flag these...

Awesome! 

I haven't seen it in the wild, but there's this too:

dict_of_values.update(key=some_value)



-- 
Steven

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


Re: Idiosyncratic python

2015-09-24 Thread Steven D'Aprano
On Thu, 24 Sep 2015 04:54 pm, Ben Finney wrote:

> Steven D'Aprano  writes:
> 
>> On Thursday 24 September 2015 16:16, Paul Rubin wrote:
>>
>> > Steven D'Aprano  writes:
>> >> for k, v in mydict.items():
>> >> del(k)
>>
>> […] The obvious intent is to iterate over the *values* of the
>> dictionary, but the coder didn't know about values, so he iterated
>> over (key,value) pairs, then deleted the key local variable (not the
>> key in the dict!) to keep the namespace clean.
> 
> That's not obvious to me. It's plausible, now that you say it. I find it
> also plausible, though, that the author is under the mistaken impression
> that the key and value must both be deleted, and has found a way that
> appears to do that.

In fairness, I have seen the rest of the loop, which I excised, and it uses
the value v. There's no hint that the author thinks the dict has been
cleared by the end of the loop.




-- 
Steven

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


Re: ConnectionError handling problem

2015-09-24 Thread shiva upreti
Thank you. I didnt know about keyboard interrupt exception.
It means my code hangs without raising any exceptions, what should i do in this 
case?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ConnectionError handling problem

2015-09-24 Thread shiva upreti
Thank you Cameron.
I think the problem with my code is that it just hangs without raising any 
exceptions. And as mentioned by Laura above that when I press CTRL+C, it just 
catches that exception and prints ConnectionError which is definitely a lie in 
this case as you mentioned.
As my code doesnt raise any exception by itself, instead just hangs, I wont be 
able to characterize the exceptions and handle them individually.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ConnectionError handling problem

2015-09-24 Thread Cameron Simpson

On 24Sep2015 20:57, shiva upreti  wrote:

Thank you Cameron.
I think the problem with my code is that it just hangs without raising any 
exceptions. And as mentioned by Laura above that when I press CTRL+C, it just 
catches that exception and prints ConnectionError which is definitely a lie in 
this case as you mentioned.


Update it to report the _actual_ exception received. (If any.) At least then 
you will be sure.



As my code doesnt raise any exception by itself, instead just hangs,


So, no "ConnectionError" message?


I wont be able to characterize the exceptions and handle them individually.


Can you repost you code once it is modified to display the precise exception.

Note that one easy way to catch all but progressively handle specific 
exceptions looks like this:


 try:
... code ...
 except OSError as e:
   print OSError received, specifics are:", e
 except Exception as e:
   print "unhandled exception:", e
   break

and so on, inserting the exception types _above_ the final "except" as you add 
actions for them.


Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Re: ConnectionError handling problem

2015-09-24 Thread shiva upreti
On Thursday, September 24, 2015 at 4:09:04 PM UTC+5:30, Laura Creighton wrote:
> In a message of Wed, 23 Sep 2015 19:49:17 -0700, shiva upreti writes:
> >Hi
> >If my script hangs because of the reasons you mentioned above, why doesnt it 
> >catch ConnectionError?
> >My script stops for a while and when I press CTRL+C, it shows 
> >ConnectionError without terminating the process, and the script resumes from 
> >where it left off.
> 
> This is exactly what you asked it to do. :)
> 
> >>try:
> >>r=requests.post(url, data=query_args)
> >>except:
> >>print "Connection error"
> >>time.sleep(30)
> >>continue
> 
> try to do something until you get an Exception.  Since that is a
> naked except, absolutely any Exception will do.  That you
> print out 'Connection error' doesn't mean that you are only
> catching exceptions raised by trying to send something to the
> other end ... any Exception will do.
> 
> So what happens when you press Control-C?
> 
> You get a KeyboardInterrupt exception! :)
> 
> see: https://docs.python.org/2/library/exceptions.html
> 
> And  you are catching it :)
> And when you catch it you print  Connection error and keep on
> trying.
> 
> This is why people were telling you that naked try:except: pairs,
> are rarely what you want.  You didn't want to catch control-c but
> you caught it anyway.
> 
> Laura

Thank you. I didnt know about keyboard interrupt exception.
It means my code hangs without raising any exceptions, what should i do in this 
case? 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ConnectionError handling problem

2015-09-24 Thread shiva upreti
On Thursday, September 24, 2015 at 4:09:04 PM UTC+5:30, Laura Creighton wrote:
> In a message of Wed, 23 Sep 2015 19:49:17 -0700, shiva upreti writes:
> >Hi
> >If my script hangs because of the reasons you mentioned above, why doesnt it 
> >catch ConnectionError?
> >My script stops for a while and when I press CTRL+C, it shows 
> >ConnectionError without terminating the process, and the script resumes from 
> >where it left off.
> 
> This is exactly what you asked it to do. :)
> 
> >>try:
> >>r=requests.post(url, data=query_args)
> >>except:
> >>print "Connection error"
> >>time.sleep(30)
> >>continue
> 
> try to do something until you get an Exception.  Since that is a
> naked except, absolutely any Exception will do.  That you
> print out 'Connection error' doesn't mean that you are only
> catching exceptions raised by trying to send something to the
> other end ... any Exception will do.
> 
> So what happens when you press Control-C?
> 
> You get a KeyboardInterrupt exception! :)
> 
> see: https://docs.python.org/2/library/exceptions.html
> 
> And  you are catching it :)
> And when you catch it you print  Connection error and keep on
> trying.
> 
> This is why people were telling you that naked try:except: pairs,
> are rarely what you want.  You didn't want to catch control-c but
> you caught it anyway.
> 
> Laura

Thank you. I didnt know about keyboard interrupt exception.
It means my code hangs without raising any exceptions, what should i do in this 
case? 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ConnectionError handling problem

2015-09-24 Thread shiva upreti
On Friday, September 25, 2015 at 10:55:45 AM UTC+5:30, Cameron Simpson wrote:
> On 24Sep2015 20:57, shiva upreti  wrote:
> >Thank you Cameron.
> >I think the problem with my code is that it just hangs without raising any 
> >exceptions. And as mentioned by Laura above that when I press CTRL+C, it 
> >just catches that exception and prints ConnectionError which is definitely a 
> >lie in this case as you mentioned.
> 
> Update it to report the _actual_ exception received. (If any.) At least then 
> you will be sure.
> 
> >As my code doesnt raise any exception by itself, instead just hangs,
> 
> So, no "ConnectionError" message?
> 
> >I wont be able to characterize the exceptions and handle them individually.
> 
> Can you repost you code once it is modified to display the precise exception.
> 
> Note that one easy way to catch all but progressively handle specific 
> exceptions looks like this:
> 
>   try:
>  ... code ...
>   except OSError as e:
> print OSError received, specifics are:", e
>   except Exception as e:
> print "unhandled exception:", e
> break
> 
> and so on, inserting the exception types _above_ the final "except" as you 
> add 
> actions for them.
> 
> Cheers,
> Cameron Simpson 

Hi Cameron.
I think you may have misunderstood my problem.
When my code runs it doesnt throw any exception. It just hangs(stops executing) 
for unknown reasons. I want to know why. It doesnt even throw ConnectionError 
unless I press CTRL+C(only because I hard coded ConnectionError).
I can repost the whole problem again if you want me to.
Thanks.:)

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


Re: Modifying signature of ctor in class

2015-09-24 Thread gal kauffman
Sorry, you really can't give FunctionType an argument list.
Maybe you can wrap the function with a callable object, this way you can
change the argument list returned, and doest have to eval or compile code.
On Sep 25, 2015 12:46 AM, "Joseph L. Casale" 
wrote:

> > I don't think you can easily change the function's own definition,
> > other than by using eval (or equivalent shenanigans, like crafting
> > your own bytecode); but as of Python 3.something, the help() function
> > looks for a __wrapped__ attribute and will take function args from
> > that instead of the function itself. That way, when you use
> > functools.wraps(), it copies in the docstring and stuff, and as far as
> > help() is concerned, copies in the argument list too.
> >
> > No idea whether you'll be able to do that too, but it's a fairly
> > effective way to get around the problem if you can.
>
> Hi Chris,
> That is helpful. It still leaves me with generating a string function
> and eval'ing or compiling it to swipe the sig. At the point I could
> rebuild the entire function and simply apply it.
>
> Where all but a valid sig helps is for introspection such as tab completing
> with ipython or using an IDE etc.
>
> Thanks everyone,
> jlc
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Modifying signature of ctor in class

2015-09-24 Thread gal kauffman
You can use the FunctionType class found in the types module (and its
friends) to create functions on the run.
And you can use the 'inspect' module to inspect existing functions, if you
need to base the new function on an existing one.
On Sep 24, 2015 11:28 PM, "Joseph L. Casale" 
wrote:

> I have a class factory where I dynamically add a constructor to the class
> output.
> The method is a closure and works just fine, however to accommodate the
> varied
> input its signature is (*args, **kwargs).
>
> While I modify the doc strings, the ctor sig is not optimal. Without
> building
> this a string and using eval, is there anything that can be done about
> this?
>
> Thanks,
> jlc
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Problem to calculate the mean in version 3.4

2015-09-24 Thread Michel Guirguis
Good morning,

I have downloaded the version 3.4 and I have a problem to calculate the mean. 
The software does not recognise the function mean(). I am getting the following 
error.

>>> mean([1, 2, 3, 4, 4])
Traceback (most recent call last):
  File "", line 1, in 
mean([1, 2, 3, 4, 4])
NameError: name 'mean' is not defined

Could you please help. Is it possible to send me the version that calculate 
statistics.

Thanks,

Michel





9.7. statistics — Mathematical statistics functions
New in version 3.4.

Source code: Lib/statistics.py

This module provides functions for calculating mathematical statistics of 
numeric (Real-valued) data.

NoteUnless explicitly noted otherwise, these functions support int, float, 
decimal.Decimal and fractions.Fraction. Behaviour with other types (whether in 
the numeric tower or not) is currently unsupported. Mixed types are also 
undefined and implementation-dependent. If your input data consists of mixed 
types, you may be able to use map() to ensure a consistent result, e.g. 
map(float,input_data).
9.7.1. Averages and measures of central location
These functions calculate an average or typical value from a population or 
sample.

mean()  Arithmetic mean (“average”) of data.
median()Median (middle value) of data.
median_low()Low median of data.
median_high()   High median of data.
median_grouped()Median, or 50th percentile, of grouped data.
mode()  Mode (most common value) of discrete data.
9.7.2. Measures of spread
These functions calculate a measure of how much the population or sample tends 
to deviate from the typical or average values.

pstdev()Population standard deviation of data.
pvariance() Population variance of data.
stdev() Sample standard deviation of data.
variance()  Sample variance of data.
9.7.3. Function details
Note: The functions do not require the data given to them to be sorted. 
However, for reading convenience, most of the examples show sorted sequences.

statistics.mean(data)
Return the sample arithmetic mean of data, a sequence or iterator of 
real-valued numbers.

The arithmetic mean is the sum of the data divided by the number of data 
points. It is commonly called “the average”, although it is only one of many 
different mathematical averages. It is a measure of the central location of the 
data.

If data is empty, StatisticsError will be raised.

Some examples of use:

>>>
>>> mean([1, 2, 3, 4, 4])
2.8
>>> mean([-1.0, 2.5, 3.25, 5.75])
2.625


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