Re: Late-binding of function defaults (was Re: What is a function parameter =[] for?)

2015-11-19 Thread dieter
Chris Angelico  writes:

> On Fri, Nov 20, 2015 at 5:42 AM, Ian Kelly  wrote:
>> BartC on the other hand is just complaining about an aspect of Python
>> that is legitimately controversial.
>
> IMO it's controversial mainly because there's an easy and obvious
> syntax for early binding, but late binding doesn't have syntactic
> support, and all the options are imperfect.

I do not think that we should get additional syntax for lately bound
default values. It would explicitely introduce the concepts
early versus late binding which are likely difficult to understand
by many users.

In addition, the last few days have had two discussions in this list
demonstrating the conceptial difficulties of late binding -- one of them:

  Why does "[lambda x: i * x for i in range(4)]" gives
  a list of essentially the same functions?


Note as well, that it is difficult to define what "late binding"
should mean in non-trivial cases:

   def f(..., a=)

   If "a" is lately bound, when are bound the variables involved
   in its defining expression?

   If they are early bound, you get the same effect as with realy
   bound default parameters: calling the function can change non local
   objects which may lead to surprises.

   If they are lately bound, the references may no longer be
   resolvable or (worse) may resolve to unexpected objects.


If you need late binding, you might use something like this:

   class Late(object):
 def __init__(self, obj): self.obj = obj
 def bind:
   from copy import deepcopy
   return deepcopy(obj)
 def __repr__: ...

   def f(..., a=Late()):
 ...
 a = a.bind()
 ...

Of course, you could define a decorator which performs the
"bind" calls automatically.




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


Plotting a timeseris graph from pandas dataframe using matplotlib

2015-11-19 Thread Karthik Sharma
I have the following data in a csv file 

   SourceIDBSs   hour   Type
7208   87 11MAIN
11060  67 11MAIN
3737   88 11MAIN
9683   69 11MAIN
9276   88 11MAIN
7754   62 11MAIN
1  80 12MAIN
9276   88 12MAIN
1  80 12MAIN
6148   70 12MAIN
1  80 12MAIN
9866   80 12SUB
9866   78 13MAIN
9866   78 13SUB
20729  82 14MAIN
9276   88 14MAIN
1  80 15MAIN
20190  55 15MAIN
7208   85 15MAIN
7208   86 15MAIN
7754   61 16MAIN
8968   91 16MAIN
3737   88 16MAIN
9683   69 16MAIN
20729  81 16MAIN
9704   68 16MAIN
1  87 16PAN


I have the following python code.I want to plot a graph with the following 
specifications.

For each `SourceID` and `Type` I want to plot a graph of `BSs` over time. I 
would prefer if each `SourceID` and `Type` is a subplot on single plot.I have 
tried a lot of options using groupby, but can't seem to get it work.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt



COLLECTION = 'NEW'
DATA = r'C:\Analysis\Test\{}'.format(COLLECTION)
INPUT_FILE = DATA + r'\in.csv'
OUTPUT_FILE = DATA + r'\out.csv'


with open(INPUT_FILE) as fin:
df = pd.read_csv(INPUT_FILE,
  usecols=["SourceID", 'hour','BSs','Type'],
  header=0)

df.drop_duplicates(inplace=True)

df.reset_index(inplace=True)

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


Re: Why doesn't this method have access to its "self" argument?

2015-11-19 Thread dieter
Robert Latest via Python-list  writes:

> I'm still trying to find a simple way to implement a method (but not the
> full class) in C. Suggestions I have recived so far are good, but seem to be
> over the top for such a (seemingly) simple problem.

The C interface of Python is far from simple - and it is very easy
to make severe and difficult to analyse errors. Therefore, I confirm
an advice you already got: use "cython" (which drastically reduces
the danger of errors).

A "method" in Python is just a function which happens to get automatically
on call an additional first arguemnt: the object's reference. Apparently,
this automatism does not work for C implemented functions (at least
in Python 2). You would need to use a (so called) "descriptor" wrapper
to do this explicitely.

The easiest way (in my view), however would be:

import _my_c_implementation

class C(object):
  def my_method(self, *args, **kw):
return _my_c_implementation.my_method(self, *args, **kw)


With a descriptor "method" (sketched above), this would become:

class C(object):
  my_method = method(_my_c_implementation.my_method)

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


Re: PubMed / Entrez

2015-11-19 Thread dieter
 writes:

> I am looking for a way to use the PubMed (medical research search
> engine) API (aka Entrez) with Python3.

I am using (on Python 2) "urllib" and "lxml" to interface with
the NCBI E-utilities.

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


Re: failing to run python on my pc

2015-11-19 Thread boB Stepp
On Thu, Nov 19, 2015 at 2:22 PM, Daniel Kasuza  wrote:
> Dear Sir/Madam
> I am student with University of the people and a beginner in programming.
> My problem is that l have down loaded python 2.7 but l am failing to muse
> it. If l try to to use it, I am getting an option which say run. If l press
> run, it just run and come back to the same option. I want to use it for
> some practice but i am failing.

Your question is rather vague and difficult to understand.  Are you
having difficulty in installing Python 2.7?  If yes, what operating
system are you using?  Did your course or course text book give you
instructions on what to do?  If so, what steps did you accomplish
successfully, and at what step did things stop working?

Or do you have Python installed and then tried to run a program?  What
program and how did you try to run it?  What were the precise results?

You might want to redirect your question to Python Tutor with a much
fuller description of what you tried and what happened:
https://mail.python.org/mailman/listinfo/tutor

This mailing list is targeted towards beginners in Python.  They have
been extremely helpful to me!  But you will have to give much more
detailed information before anyone will be able to assist you.  Also,
the main Python website has many resources, including tutorials as
well as the full docs.  Poke around at www.python.org .  And don't
forget to search the 'Net!  Your exact problem has probably been
encountered many times before ...


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


Re: Generate a random list of numbers

2015-11-19 Thread Seymore4Head
On Fri, 20 Nov 2015 15:38:36 +1100, Steven D'Aprano
 wrote:

>On Fri, 20 Nov 2015 03:05 pm, Seymore4Head wrote:
>
>> Why does a work and b doesn't?  What I was trying to accomplish with b
>> is to get a random list (of random length) that could have digits
>> repeat.
>> 
>> I got idea for both methods from the Internet.  I do see that one uses
>> brackets and the other doesn't, but I don't know the difference.
>> 
>> import random
>> for i in range (5):
>> a = random.sample(range(10), random.randrange(3,6))
>> print a
>
>Break it up, step by step.
>
>range(10) produces a list from 0 to 9. random.randrange(3, 6) produces a
>single integer from 3 to 5 (6 is excluded). Let's say by chance it produces
>the number 4.
>
>Then random.sample takes the list, and the integer 4, and selects 4 values
>at random from the list. Say, something like this:
>
>[8, 6, 7, 0]
>
>Note that random.sample does NOT repeat selections. The numbers will always
>be unique.
>
>
>
>> for i in range (5):
>> b = [random.randrange (10), random.randrange(4,8)]
>> print b
>
>As above, run through this step by step.
>
>random.randrange(10) produces a single number at random between 0 and 9 (10
>is excluded). Let's say it picks 8. 
>
>random.randrange(4,8) produces a single number at random between 4 and 7 (8
>is excluded). Let's say it picks 5.
>
>Then b is set to the list [8, 5].
>
>This list will always have two items.
>
>
>
>If you want a random number of digits that might repeat:
>
>[random.randrange(10) for i in range(random.randrange(1, 21))]
>
>will produce a random number between 1 and 20 (21 is excluded). Let's say it
>picks 6.
>
>then range(6) produces the list [0, 1, 2, 3, 4, 5], and "for i in range..."
>will iterate over those values. Although i is not used, this ends up
>looping 6 times.
>
>For each loop, random.randrange(10) produces a random digit between 0 and 9
>(10 is excluded). So we end up with something like:
>
>[6, 4, 2, 2, 6, 9]
>
>for example.

That works.
Thanks
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Generate a random list of numbers

2015-11-19 Thread Steven D'Aprano
On Fri, 20 Nov 2015 03:05 pm, Seymore4Head wrote:

> Why does a work and b doesn't?  What I was trying to accomplish with b
> is to get a random list (of random length) that could have digits
> repeat.
> 
> I got idea for both methods from the Internet.  I do see that one uses
> brackets and the other doesn't, but I don't know the difference.
> 
> import random
> for i in range (5):
> a = random.sample(range(10), random.randrange(3,6))
> print a

Break it up, step by step.

range(10) produces a list from 0 to 9. random.randrange(3, 6) produces a
single integer from 3 to 5 (6 is excluded). Let's say by chance it produces
the number 4.

Then random.sample takes the list, and the integer 4, and selects 4 values
at random from the list. Say, something like this:

[8, 6, 7, 0]

Note that random.sample does NOT repeat selections. The numbers will always
be unique.



> for i in range (5):
> b = [random.randrange (10), random.randrange(4,8)]
> print b

As above, run through this step by step.

random.randrange(10) produces a single number at random between 0 and 9 (10
is excluded). Let's say it picks 8. 

random.randrange(4,8) produces a single number at random between 4 and 7 (8
is excluded). Let's say it picks 5.

Then b is set to the list [8, 5].

This list will always have two items.



If you want a random number of digits that might repeat:

[random.randrange(10) for i in range(random.randrange(1, 21))]

will produce a random number between 1 and 20 (21 is excluded). Let's say it
picks 6.

then range(6) produces the list [0, 1, 2, 3, 4, 5], and "for i in range..."
will iterate over those values. Although i is not used, this ends up
looping 6 times.

For each loop, random.randrange(10) produces a random digit between 0 and 9
(10 is excluded). So we end up with something like:

[6, 4, 2, 2, 6, 9]

for example.



-- 
Steven

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


Re: shorten "compress" long integer to short ascii.

2015-11-19 Thread Paul Rubin
Vincent Davis  writes:
> My goal is to shorten a long integer into a shorter set of characters.
> Below is what I have which gets me about a 45-50% reduction. Any suggestion
> on how to improve upon this?

You can't improve much.  A decimal digit carries log(10,2)=3.32 bits
of information.  A reasonable character set for Twitter-style links
might have 80 or so characters (upper/lower alphabetic, digits, and
a dozen or so punctuation characters), or log(80,2)=

> I not limited to ascii but I didn't see how going to utf8 would help.

If you could use Unicode characters like Chinese ideographs, that gives
you a much larger alphabet to work with, so you'd need fewer chars
displayed in the link, but they'd be hard for most people to type.

> l = string.ascii_lowercase + string.ascii_uppercase +
> '!"#$%&\'()*+,-./:;<=>?@[]^_`{|}~'

OK, 83 chars, but it may not be ok to use some of them like #, /, and ?,
since they can have special meanings in urls.

Your algorithm looks basically ok though I didn't examine it closely.
Here is my shortened version:

  import string

  # alphabet here is 83 chars
  alphabet = string.ascii_lowercase + \
   string.ascii_uppercase +'!"#$%&\'()*+,-./:;<=>?@[]^_`{|}~'
  alphabet_size = len(alphabet)

  decoderdict = dict((b,a) for a,b in enumerate(alphabet))

  def encoder(integer):
  a,b = divmod(integer, alphabet_size)
  if a == 0: return alphabet[b]
  return encoder(a) + alphabet[b]

  def decoder(code):
return reduce(lambda n,d: n*alphabet_size + decoderdict[d], code, 0)

  def test():
  n = 92928729379271
  short = encoder(n)
  backagain = decoder(short)
  nlen = len(str(n))
  print (nlen, len(short), float(len(short))/nlen)
  assert n==backagain, (n,short,b)

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


Generate a random list of numbers

2015-11-19 Thread Seymore4Head
Why does a work and b doesn't?  What I was trying to accomplish with b
is to get a random list (of random length) that could have digits
repeat.  

I got idea for both methods from the Internet.  I do see that one uses
brackets and the other doesn't, but I don't know the difference.

import random
for i in range (5):
a = random.sample(range(10), random.randrange(3,6))
print a

for i in range (5):
b = [random.randrange (10), random.randrange(4,8)]
print b

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


Re: Writing a Financial Services App in Python

2015-11-19 Thread William Ray Wing

> On Nov 19, 2015, at 6:59 AM, Cai Gengyang  wrote:
> 
> 
> From YCombinator's new RFS, This is the problem I want to solve as it is a 
> severe problem I face myself and something I need. I want to write this app 
> in Python as I heard that Python is a great language that many programmers 
> use ... How / where do I start ? The problem is detailed below :
> 
> FINANCIAL SERVICES
> 

[Big edit]

You might enjoy reading the note here:  
http://www.wsj.com/articles/an-algo-and-a-dream-for-day-traders-1439160100?mod=djem10point

Which, among other things, points out that DIY algorithmic trading is the 
latest DIY craze.

Bill


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


shorten "compress" long integer to short ascii.

2015-11-19 Thread Vincent Davis
My goal is to shorten a long integer into a shorter set of characters.
Below is what I have which gets me about a 45-50% reduction. Any suggestion
on how to improve upon this?
I not limited to ascii but I didn't see how going to utf8 would help.
The resulting string needs to be something I could type/paste into twitter
for example.

On a side note string.punctuation contains "\\" what is \\ ?

import string
import random

# Random int to shorten
r = random.getrandbits(300)
lenofr = len(str(r))

l = string.ascii_lowercase + string.ascii_uppercase +
'!"#$%&\'()*+,-./:;<=>?@[]^_`{|}~'
n = [str(x) for x in list(range(10,93))]
decoderdict = dict(zip(l, n))
encoderdict = dict(zip(n, l))

def encoder(integer):
s = str(integer)
ls = len(s)
p = 0
code = ""
while p < ls:
if s[p:p+2] in encoderdict.keys():
code = code + encoderdict[s[p:p+2]]
p += 2
else:
code = code + s[p]
p += 1
return code

def decoder(code):
integer = ""
for c in code:
if c.isdigit():
integer = integer + c
else:
integer = integer + decoderdict[c]
return int(integer)

short = encoder(r)
backagain = decoder(short)

print(lenofr, len(short), len(short)/lenofr, r==backagain)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why won't this run?

2015-11-19 Thread Mike S via Python-list

On 11/15/2015 12:38 PM, jbak36 wrote:

Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit 
(AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.

#this program says hello and asks for my name
print:('Hello world!')

Hello world!

print:('What is your name?') #ask for their name

What is your name?

myName = input()

print:('It is good to meet you,'+myName)

print:('The length of your name is:')

The length of your name is:

print:(len(myName))

39

print:('What is your age?')#ask for their age

What is your age?

myAge=input()

print:('You will be ' + str(int(myAge)+1)'in a year.')


>>> print("Hello World")
Hello World
>>> myname=input("What is your name? ")
What is your name? John
>>> print ("Your name is ", myname)
Your name is  John

...you can find code samples in the *quick tutorial listed here: 
https://wiki.python.org/moin/BeginnersGuide/Programmers

*http://hetland.org/writing/instant-python.html
--
https://mail.python.org/mailman/listinfo/python-list


Re: how do I learn python ?

2015-11-19 Thread Mike S via Python-list

On 11/19/2015 1:00 AM, Michiel Overtoom wrote:



On 18 Nov 2015, at 05:58, 夏华林  wrote:
(nothing)


You might want to start at https://www.python.org/about/gettingstarted/

PS. Leaving the body of an email or usenet article empty is considered bad form.

Greetings,


Thanks for that, there is a great list of tutorials there!
https://wiki.python.org/moin/BeginnersGuide/Programmers

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


Re: What is a function parameter =[] for?

2015-11-19 Thread Steven D'Aprano
On Fri, 20 Nov 2015 04:30 am, BartC wrote:

> On 19/11/2015 16:01, Steven D'Aprano wrote:
[...]

> The whole concept of 'mutable' default is alien to me. A default is just 
> a convenient device to avoid having to write:
> 
>fn(0) or fn("") or fn([])

Says who?

Here's another use for function defaults, as static storage:


# Ackermann's function
def ack(m, n, _memo={}):
key = m, n
if key not in _memo:
if m==0: v = n + 1
elif n==0: v = ack(m-1, 1)
else: v = ack(m-1, ack(m, n-1))
_memo[key] = v
return _memo[key]


This is a quick and easy way to memoise a function which would otherwise be
horribly slow. And it only works because _memo is bound to a mutable object
once, and once only.

 
> You just write fn() instead. But it shouldn't come at the cost of
> completely different semantics! Because then it can't really be called a
> default value at all.

But it doesn't come with completely different semantics. This is the stock
standard semantics for assignment.

Since we're not passing an argument, let's get rid of the argument
altogether. If we put the assignment inside the body of the function, that
code is executed every time the function is called. "arg" gets a brand new,
empty list each time:

def test():
arg = []
arg.append(1)
return len(arg)


If we put the assignment *outside* of the body of the function, that code is
executed once only, and the same list is used over and over again:

arg = []
def test():
arg.append(1)
return len(arg)



This is *exactly* the same semantics as for parameter defaults (except that
they aren't stored as globals, but as hidden fields deep inside the
function object itself). Now, look at the function declaration:


def test(arg=[]):
arg.append(1)
return len(arg)


The binding arg=[] is NOT inside the body of the function. Therefore, it is
NOT executed repeatedly, but only once.


>   isn't surprising to
>> somebody coming from a completely different paradigm. I was surprised by
>> it too, the first time I got bitten.
> 
> So you didn't bother reading the LRM either!

LRM? Left Right Manual?

No, I read it. I knew that the list was only created once. But like I said,
I didn't follow the implications of that. If it is only created once, and
you modify the value, the value will be modified.


>> py> def demo_const(x, y=[]):
>> ... return x + len(y)
> 
>> Exactly as you should expect. Where you run into trouble is when the
>> default value is NOT a constant:
>>
>> py> def demo_variable(x, y=[]):
>> ... y.append(1)
>> ... return x + len(y)
> 
> Sorry, what is the default value in each of these? As the first lines of
> the defintions look identical apart from the function names.

The *value* is whatever contents the list holds.

a = []
a.append(1)
a.append(2)
a.append(3)

What's the value of a? Are you shocked and horrified to discover that the
value of a is not the empty list, but the list [1, 2, 3]?



>> py> demo_variable(5)
>> 6
>> py> demo_variable(5)
>> 7
>> py> demo_variable(5)
>> 8
>>
>>
>> If you modify the value, the value will be modified. Why are you
>> surprised by this?
> 
> Which value is being modified? The []?

The object bound to y is being modified. y.append(1) modifies the object
bound to y. That object gets taken from the defaults if you don't supply a
value yourself. That default object starts of life as an empty list, but it
doesn't stay empty if you append to it.



 When you deal with mutable objects, you have to expect them to mutate.
 The whole point of mutability is that their value can change.
>>>
>>> That [] doesn't look like an object that could change.
>>
>> Of course it does.
> 
> You've lost me know.
> 
> Are you saying that:
> 
>a=[]
> 
> why sometimes not assign an empty list, because that [] could have been
> modified?

No. But [] is syntax for an empty list, and lists can change -- they are
mutable.

a = []
a.append(1)

Are you shocked to learn that a is no longer an empty list? (I know I asked
a similar question before, but this is an important point.)


>> It is a list literal, like int literals, float literals,
>> string literals and the rest.
> 
> Another surprise? Literals by definition can't change:

Says who? The existence of literal syntax is a feature of the programming
language. The mutability of values is a *separate* feature. The two are
unrelated.


> def fn():
> a=[10,20,30]
> a.append(999)
> 
> I would hope that a is set to [10,20,30] at each entry to the function!

Naturally. Each time you call the function, the body of the function
executes and creates a new list. You take that list, and then modify it in
the very next line with a.append(999).

What happens if you only create the list *once*?

a = [10,20,30]
def fn():
a.append(999)
print(a)


Are you surprised that a doesn't get reset to [10, 20, 30] each time you
call the function?


>> Assignments are not copies at all.
> 
> if you write A=B then something of B needs

Re: What is a function parameter =[] for?

2015-11-19 Thread Laura Creighton
In a message of Thu, 19 Nov 2015 16:36:17 -0800, Ned Batchelder writes:
>On Thursday, November 19, 2015 at 7:28:44 PM UTC-5, Steven D'Aprano wrote:
>> On Fri, 20 Nov 2015 05:50 am, BartC wrote:
>> 
>> 
>> > I said that Python's "=" does a very shallow copy. And I stated that in
>> > A=B, something of B must be copied into A.
>> > 
>> > I (and probably others) would like to know why none of that is correct.
>> > But I suspect I'm not wrong.
>> 
>> Nothing of B is copied.
>
>I think we are stuck in a simple terminology conflict here.  There is something
>of B copied.  The name B refers to a value.  In CPython, that reference is a
>pointer.  That pointer (the memory address) is copied from B to A.
>
>Nothing of "B's value", that is, the object B is referring to, is copied. But
>there is something about B (the pointer to its value) that is now also 
>something
>about A, because A also has that pointer.
>
>--Ned.

In PyPy we do this too.
But we don't copy a memory-address pointer.
We have a moving garbage collector, and no objects are in any way
guaranteed to be at their last memory address.

We copy a thing that, when you ask it nicely, spits out "where the hell
is the object right now,  because I want to modify it."

But this thing is in no way tied to any particular place in any DRAM.
It hits PyPy at an abstraction layer above that of 'we write 1s and 0s
here' so if you want to implement python on a message passing system
implemented by carrier pigeon, we could do this.  It would be slow,
however. :)

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


Re: What is a function parameter =[] for?

2015-11-19 Thread Ian Kelly
On Nov 19, 2015 5:31 PM, "Steven D'Aprano"  wrote:
>
> [Aside: there is some ambiguity here. If I say "a reference to B", I
> actually mean a reference to the object referenced to by B. I don't mean a
> reference to the *name* B. Python doesn't support that feature: names are
> not values in Python.]

Quoting BartC:

"""
if you write A=B then something of B needs to have been copied into A, even
if it's just the reference that B contains. Otherwise it would be difficult
to get A to refer to the same object as B.
"""

If you're trying to draw some distinction between what BartC wrote 17 posts
back and what you wrote here, I'm not seeing it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-19 Thread Ned Batchelder
On Thursday, November 19, 2015 at 7:28:44 PM UTC-5, Steven D'Aprano wrote:
> On Fri, 20 Nov 2015 05:50 am, BartC wrote:
> 
> 
> > I said that Python's "=" does a very shallow copy. And I stated that in
> > A=B, something of B must be copied into A.
> > 
> > I (and probably others) would like to know why none of that is correct.
> > But I suspect I'm not wrong.
> 
> Nothing of B is copied.

I think we are stuck in a simple terminology conflict here.  There is something
of B copied.  The name B refers to a value.  In CPython, that reference is a
pointer.  That pointer (the memory address) is copied from B to A.

Nothing of "B's value", that is, the object B is referring to, is copied. But
there is something about B (the pointer to its value) that is now also something
about A, because A also has that pointer.

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


Re: Late-binding of function defaults (was Re: What is a function parameter =[] for?)

2015-11-19 Thread Steven D'Aprano
On Fri, 20 Nov 2015 07:57 am, Marko Rauhamaa wrote:

> Laura Creighton :
> 
>> My experience says that the people who are confused want lists to
>> behave like tuples. period. i.e. they don't want lists to be mutable.
> 
> I think it's simpler than that. When you have:
> 
>def f(x=[]):
>y = []
> 
> the first [] is evaluated when "def" is executed, while the latter [] is
> evaluated whenever "f" is executed. It's easy to be confused.

It shouldn't be. The function declaration 

def f(x=[]):

is executed only once. The function body, conveniently indented to make it
stand out:

y = []

is executed every time you call the function. 


[Aside: that nice clean design is somewhat muddied by docstrings. Despite
being indented, docstrings are actually part of the declaration in the
sense that they are handled only once, at function definition time.]


-- 
Steven

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


Re: What is a function parameter =[] for?

2015-11-19 Thread Steven D'Aprano
On Fri, 20 Nov 2015 05:50 am, BartC wrote:


> I said that Python's "=" does a very shallow copy. And I stated that in
> A=B, something of B must be copied into A.
> 
> I (and probably others) would like to know why none of that is correct.
> But I suspect I'm not wrong.

Nothing of B is copied.

Here is a terrible ASCII art diagram of an object, floating in memory (most
likely in the heap), an instant before the garbage collector can reach it
and collect it:

   +--+
   |  DEADBEEF0012345...  |
   +--+

(Best viewed in a monospaced font, like Courier.)

The contents of the object are shown as a hex-dump, and will depend on the
actual object and its value, but in general you would expect a field which
acts as some sort of tag or pointer linking the instance to its parent
class, plus other fields specifying the object's value and/or attributes.
The internal details of the object don't matter, but basically objects are
structs or records.

Here is an ASCII art diagram of that same object, now bound to the name "B",
preventing the GC from collecting it:

   +--+
B->|  DEADBEEF0012345...  |
   +--+

The name "B" may be on the heap, or in an array. It is possible that the
human-readable string "B" itself no longer appears in memory. I don't care
about the specific implementation, but for the record, in the case of
CPython the name "B" is itself a string object in the heap, linked to from
a specific associative array (hash table) also in the heap. (I think.)

The link between the name B and the object ---> could be anything that
allows the compiler/interpreter to associate one to the other. We call it
a "reference". In CPython, references are pointers. If somebody were to
write Python using FORTRAN 77, they would most likely use a big array to
hold the objects, and use the index into the array as references. Other
implementations may use other things, but for simplicity, let's just stick
with calling it a pointer.

Now let's do the assignment A = B:

   +--+
B->|  DEADBEEF0012345...  |
+->+--+
|
A---+

This adds a new reference (think: pointer) to the object, linked to the
name "A". But **nothing of the object** is copied. The pointers to the
object are not part of the object -- they are external to the object.

If you want to talk about anything being copied, you should talk about
*copying the reference* to B, not copying B.

[Aside: there is some ambiguity here. If I say "a reference to B", I
actually mean a reference to the object referenced to by B. I don't mean a
reference to the *name* B. Python doesn't support that feature: names are
not values in Python.]



-- 
Steven

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


Re: What is a function parameter =[] for?

2015-11-19 Thread Ned Batchelder
On Thursday, November 19, 2015 at 7:11:52 PM UTC-5, BartC wrote:
> On 19/11/2015 22:55, Michael Torrie wrote:
> > On 11/19/2015 02:21 PM, BartC wrote:
> >> (Python returns 42; so that means my languages are more dynamic than
> >> Python? That's hard to believe!)
> >
> > It tells me your language does late binding for default arguments, which
> > does mean the default argument can dynamically change at call time,
> > which would surprise me if I didn't know about it.  Either form of
> > binding is acceptable, and I don't think it makes a language more or
> > less dynamic.
> 
> You get the expression that is specified, which can give different 
> values at different times unless it involves only constants.
> 
> It can't be exactly the same as writing an identical expression in place 
> of the missing argument, as apparently different scopes come into play 
> if names are involved.
> 
> However I mainly use them for constant values. And [] is a constant 
> value in my opinion.
> 
> -- 
> Bartc

You are not alone in being surprised by how mutable default values work.
It is a topic that comes up in every "What's Bad About Python" discussion,
and is a common question from new users of the language.

I can understand how you would view [] as a constant value.  It's true that
it is an expression that produces a consistent value each time it is
evaluated.  But that value is a list, and lists are mutable.  The examples
here all use the .append() method on that value, which changes it.

Different languages work differently.  In Python, a default value expression
for a function argument is evaluated only once, when the function is defined.
That value (in this case, the actual list) is stored with the function. The
expression is not stored, the value of the expression is. That value (the
actual list) is supplied as the value of the argument if no other value is
supplied.  If you modify that value in the function, the value is modified,
and used again at the next function call.

Again, we understand why you are surprised by this, many people are. You'll
have to accept it, it's just the way Python works.  There have been many
discussions about alternatives, and they are considered to be either too
complicated, or have other undesirable behavior, or both.

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


Re: What is a function parameter =[] for?

2015-11-19 Thread BartC

On 19/11/2015 22:55, Michael Torrie wrote:

On 11/19/2015 02:21 PM, BartC wrote:

(Python returns 42; so that means my languages are more dynamic than
Python? That's hard to believe!)


It tells me your language does late binding for default arguments, which
does mean the default argument can dynamically change at call time,
which would surprise me if I didn't know about it.  Either form of
binding is acceptable, and I don't think it makes a language more or
less dynamic.


You get the expression that is specified, which can give different 
values at different times unless it involves only constants.


It can't be exactly the same as writing an identical expression in place 
of the missing argument, as apparently different scopes come into play 
if names are involved.


However I mainly use them for constant values. And [] is a constant 
value in my opinion.


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


Re: Dabbling in web development

2015-11-19 Thread Dietmar Schwertberger

Am 19.11.2015 um 22:53 schrieb bSneddon:

I know there are a plethora of web frameworks out there for Python and to be 
serious about website developement I should learn on like Django.   Really 
thought, I just want to dabble and do some easy stuff.   Does anyone have any 
suggestons?   I have a a website hosted with a hosting company who is supposed 
to have python support but hard to know what they have installed on there 
apache server.   I have seen a few examples out there but not too many.

Maybe, you should have a look at the book "Lightweight Django".

Regards,

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


Re: Dabbling in web development

2015-11-19 Thread Laura Creighton
In a message of Fri, 20 Nov 2015 01:07:24 +0200, Marko Rauhamaa writes:
>Laura Creighton :
>
>> There are lots of other choices than Django.  
>>
>> see: https://wiki.python.org/moin/WebFrameworks/
>
>However, are there any good web applications? I have seen some heroic
>attempts but most fail miserably or at least have some annoying
>glitches.
>
>The cardinal sin of web development seems to be micromanagement. Instead
>of letting the web standards do their work, the application wants to be
>in full control with JavaScript and XML HTTP requests. The results can
>be awe-inspiring but at the same time fail at the basics. For example,
>select/copy with the mouse might not work. Fonts might be garbled. Half
>the page might be invisible and unscrollable. Or nothing will be
>displayed at all.
>
>
>Marko

But you see that whether or not you use a Heavy framework like
Django or a Microframework like Flask (which is all about how
to serve such things up  how you butcher the results is
your own business.)

Web design is a lot harder than most people who make webpages think.

So what else is new?

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


Re: Dabbling in web development

2015-11-19 Thread Laura Creighton
In a message of Fri, 20 Nov 2015 10:09:01 +1100, Chris Angelico writes:
>On Fri, Nov 20, 2015 at 9:53 AM, Laura Creighton  wrote:
>> It is not the case that 'serious website developers use heavyweight
>> systems like Django' --- lots and lots of serious developers use
>> Flask or Bottle because Django makes you do it the Django way.
>> Flask lets you do it however you like.  Professionally, our company
>> has designed a ton of websites and we use Flask nearly all of the
>> time, and Pylons the rest of the time.  If your brain is well-suited
>> for Django, by all means use that, but if it is not, then do something
>> else.
>>
>> I teach kids who are 9-12 years old, weekends.
>> Hosting their own site to support pictures of their pets is a very
>> common thing to want to do.
>
>To add to the Flask recommendation: I teach adults (mostly; one of my
>students is in high school) to use Python, SQLAlchemy, and Flask,
>putting together a classic dynamic web site model. (I also use Flask
>myself for a couple of sites, and I like it; but that recommendation
>is weak because I don't have much experience with *other* frameworks.
>So all it means is "Flask hasn't majorly annoyed me".)
>
>ChrisA

Well, I highly recommend Flask, but the tutorial was for a
different microframework, 'Bottle'.

At the time I first collected the kids, it was a better tutorial.
Now, I suspect, there are lots of great ones for both of them.
But for me, the effort of translating any tutorial into Swedish
is huge.  Especially since I need to take a reputation hit with
every Swedish grammatical error my students find.  :)  The
students of 3 years ago have fixed my Swedish problems, mostly,
I think by now in this tutorial.

Being able to speak Swedish colloquially and read it does not 
mean you can write or translate it well enough to get your product
past the hyper-critical eyes of 11-year-olds who want evidence 
that this teacher, unlike so many others, can deliver the promised
goods. :)

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


Re: Dabbling in web development

2015-11-19 Thread Marko Rauhamaa
Laura Creighton :

> There are lots of other choices than Django.  
>
> see: https://wiki.python.org/moin/WebFrameworks/

However, are there any good web applications? I have seen some heroic
attempts but most fail miserably or at least have some annoying
glitches.

The cardinal sin of web development seems to be micromanagement. Instead
of letting the web standards do their work, the application wants to be
in full control with JavaScript and XML HTTP requests. The results can
be awe-inspiring but at the same time fail at the basics. For example,
select/copy with the mouse might not work. Fonts might be garbled. Half
the page might be invisible and unscrollable. Or nothing will be
displayed at all.


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


Re: Dabbling in web development

2015-11-19 Thread Chris Angelico
On Fri, Nov 20, 2015 at 9:53 AM, Laura Creighton  wrote:
> It is not the case that 'serious website developers use heavyweight
> systems like Django' --- lots and lots of serious developers use
> Flask or Bottle because Django makes you do it the Django way.
> Flask lets you do it however you like.  Professionally, our company
> has designed a ton of websites and we use Flask nearly all of the
> time, and Pylons the rest of the time.  If your brain is well-suited
> for Django, by all means use that, but if it is not, then do something
> else.
>
> I teach kids who are 9-12 years old, weekends.
> Hosting their own site to support pictures of their pets is a very
> common thing to want to do.

To add to the Flask recommendation: I teach adults (mostly; one of my
students is in high school) to use Python, SQLAlchemy, and Flask,
putting together a classic dynamic web site model. (I also use Flask
myself for a couple of sites, and I like it; but that recommendation
is weak because I don't have much experience with *other* frameworks.
So all it means is "Flask hasn't majorly annoyed me".)

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


Re: Late-binding of function defaults (was Re: What is a function parameter =[] for?) (fwd)

2015-11-19 Thread Laura Creighton
Arrgh!

I got Ned Batchelder's email wrong.  Forgot the t.
(for somebody whose irc nick is nedbat.  )

sending this to him again.   warning any repliers that the
mail address is wrong

apologies,
Laura


--- Forwarded Message

From: Laura Creighton 
Subject: Re: Late-binding of function defaults (was Re: What is a function
 parameter =[] for?)
In-reply-to: <87d1v5emhl@elektro.pacujo.net>
References: Laura Creighton :
>
>> My experience says that the people who are confused want lists to
>> behave like tuples. period. i.e. they don't want lists to be mutable.
>
>I think it's simpler than that. When you have:
>
>   def f(x=[]):
>   y = []
>
>the first [] is evaluated when "def" is executed, while the latter [] is
>evaluated whenever "f" is executed. It's easy to be confused.
>
>
>Marko

Note: Ned Bachelder (who is probably reading this on python-list
anyway added cc on this mail, as if I am to discuss somebody, however
briefly, they deserve to hear about it.  Which may irritate him to
get 2 copies instead of one, but so it goes.  I am talking about
BartC as well, but since this is his thread, I assume he is here.)

Now back to what Marko said:

This is one of the times when it is nice to be dealing with children.
The whole notion of 'when def is executed' is not on their radar
at all.  It is all a matter of 'I write this, I want that'. :)

And with reasonable amount of authority from experience, I can
tell you that 'write it with round brackets not square ones'
makes the code *just work* for a large number of students who
only have a limited amount of patience for 'understanding 
what they are doing'.  They want to be able to do it first,
and have understanding come later (if at all).

This is the learning approach of 'training' as opposed to
'educating'.  And, for all that we _talk_ of 'educating our
children' -- what we really do, a whole lot of the time, is
train them.  The very basic skills of reading, writing (typing?) 
and arithmetic and foreign languages  need to be trained, and no
amount of understanding the theory behind such things will
ever directly translate into being able to do it.

Indeed, the best authority on the planet on 13th century French court
dances is a one-legged Frenchman, (whose name I now forget).
Although he has (or maybe had, he is likely dead by now, he lost
his leg in WW2) the education and the theory and the scholasticism, 
anybody with 2 legs, however ignorant, can dance the court dances
better. 

Sometimes you want to understand what you are doing.  Sometimes
you just want to do it.  And sometimes, well, the only real way 
to get an understanding of what you are doing is to do it more.
This is, in my opinion, Bartc's problem. He doesn't program in
python enough to understand it more.  He wants us to give him
a better theoretical understanding of Python, but for me, at 
any rate he is hitting the wrong audience.  And Ned Batchelder
is unlikely to help.  Both of us come from the practical end
of things, and write lessons and talks like the one ChrisA
recommended -- which is wonderful.  And how I wish I could 
write like that -- but they are aimed at telling a practical
python programmer 'now that you know how to do it, here is how
to understand what you do'.  And then, pedagogically, you can 
move to 'and now you understand what you have been doing, here
are some awesome cool tricks you can do to make your life easier
(and impress your friends, for a particularly nerdy set of
freinds).

I don't think that Ned works for the untrained python programmer.
And until Bart writes a bunch of code in python, for many weeks
or even months, I will not be able to help him, either.

But in my life, I end up teaching programming, often to some very
smart young people who are specialists at being trained. They want me
to train them, not educate them.  When you are 9 years old,
approaching all of life with the attitude of 'how do I get 
to spit out the results I want' is enormously adaptive.

They have the opposite problem of BartC -- they want to be excellent
programmers without understanding anything, while he wants to 
understand everything before he knows how to write decent python code.

It's a pedagogical problem.

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

--- End of Forwarded Message
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-19 Thread Michael Torrie
On 11/19/2015 02:21 PM, BartC wrote:
> (Python returns 42; so that means my languages are more dynamic than 
> Python? That's hard to believe!)

It tells me your language does late binding for default arguments, which
does mean the default argument can dynamically change at call time,
which would surprise me if I didn't know about it.  Either form of
binding is acceptable, and I don't think it makes a language more or
less dynamic.  Of course as Chris and Laura have said, a list as a
default parameter throws people off because of the semantics of
mutability, and the fact that Python's variable model does not follow
the traditional memory box model used in compiled languages like C.

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


Re: Dabbling in web development

2015-11-19 Thread Laura Creighton
In a message of Thu, 19 Nov 2015 13:53:09 -0800, bSneddon writes:

>I know there are a plethora of web frameworks out there for Python
 and to be serious about website developement I should learn on like
 Django.  Really thought, I just want to dabble and do some easy
 stuff.  Does anyone have any suggestons?  I have a a website hosted
 with a hosting company who is supposed to have python support but
 hard to know what they have installed on there apache server.  I have
 seen a few examples out there but not too many.

There are lots of other choices than Django.  

see: https://wiki.python.org/moin/WebFrameworks/

The big split is whether you want a large framework, like Django, which
comes with all the batteries included, or a micro framework, like
Flask and Bottle, which gives you more control and is a whole lot
simpler.  

It is not the case that 'serious website developers use heavyweight
systems like Django' --- lots and lots of serious developers use 
Flask or Bottle because Django makes you do it the Django way.
Flask lets you do it however you like.  Professionally, our company
has designed a ton of websites and we use Flask nearly all of the
time, and Pylons the rest of the time.  If your brain is well-suited
for Django, by all means use that, but if it is not, then do something 
else.

I teach kids who are 9-12 years old, weekends.
Hosting their own site to support pictures of their pets is a very
common thing to want to do.

I have translated this:
http://bottlepy.org/docs/dev/tutorial.html

into Swedish and we tend to get a website up and running in 3 weekends
of thinking and coding.  (This is with kids who already know Python.
Learning enough python to do this takes longer, a whole lot longer
if you only get to code on weekends -- but most of the kids who want
to do this are also willing to write code on weekdays as well.)

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


Re: Late-binding of function defaults (was Re: What is a function parameter =[] for?)

2015-11-19 Thread Laura Creighton
In a message of Thu, 19 Nov 2015 22:57:10 +0200, Marko Rauhamaa writes:
>Laura Creighton :
>
>> My experience says that the people who are confused want lists to
>> behave like tuples. period. i.e. they don't want lists to be mutable.
>
>I think it's simpler than that. When you have:
>
>   def f(x=[]):
>   y = []
>
>the first [] is evaluated when "def" is executed, while the latter [] is
>evaluated whenever "f" is executed. It's easy to be confused.
>
>
>Marko

Note: Ned Bachelder (who is probably reading this on python-list
anyway added cc on this mail, as if I am to discuss somebody, however
briefly, they deserve to hear about it.  Which may irritate him to
get 2 copies instead of one, but so it goes.  I am talking about
BartC as well, but since this is his thread, I assume he is here.)

Now back to what Marko said:

This is one of the times when it is nice to be dealing with children.
The whole notion of 'when def is executed' is not on their radar
at all.  It is all a matter of 'I write this, I want that'. :)

And with reasonable amount of authority from experience, I can
tell you that 'write it with round brackets not square ones'
makes the code *just work* for a large number of students who
only have a limited amount of patience for 'understanding 
what they are doing'.  They want to be able to do it first,
and have understanding come later (if at all).

This is the learning approach of 'training' as opposed to
'educating'.  And, for all that we _talk_ of 'educating our
children' -- what we really do, a whole lot of the time, is
train them.  The very basic skills of reading, writing (typing?) 
and arithmetic and foreign languages  need to be trained, and no
amount of understanding the theory behind such things will
ever directly translate into being able to do it.

Indeed, the best authority on the planet on 13th century French court
dances is a one-legged Frenchman, (whose name I now forget).
Although he has (or maybe had, he is likely dead by now, he lost
his leg in WW2) the education and the theory and the scholasticism, 
anybody with 2 legs, however ignorant, can dance the court dances
better. 

Sometimes you want to understand what you are doing.  Sometimes
you just want to do it.  And sometimes, well, the only real way 
to get an understanding of what you are doing is to do it more.
This is, in my opinion, Bartc's problem. He doesn't program in
python enough to understand it more.  He wants us to give him
a better theoretical understanding of Python, but for me, at 
any rate he is hitting the wrong audience.  And Ned Batchelder
is unlikely to help.  Both of us come from the practical end
of things, and write lessons and talks like the one ChrisA
recommended -- which is wonderful.  And how I wish I could 
write like that -- but they are aimed at telling a practical
python programmer 'now that you know how to do it, here is how
to understand what you do'.  And then, pedagogically, you can 
move to 'and now you understand what you have been doing, here
are some awesome cool tricks you can do to make your life easier
(and impress your friends, for a particularly nerdy set of
freinds).

I don't think that Ned works for the untrained python programmer.
And until Bart writes a bunch of code in python, for many weeks
or even months, I will not be able to help him, either.

But in my life, I end up teaching programming, often to some very
smart young people who are specialists at being trained. They want me
to train them, not educate them.  When you are 9 years old,
approaching all of life with the attitude of 'how do I get 
to spit out the results I want' is enormously adaptive.

They have the opposite problem of BartC -- they want to be excellent
programmers without understanding anything, while he wants to 
understand everything before he knows how to write decent python code.

It's a pedagogical problem.

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


Re: Dabbling in web development

2015-11-19 Thread Mark Lawrence

On 19/11/2015 21:53, bSneddon wrote:

I know there are a plethora of web frameworks out there for Python and to be 
serious about website developement I should learn on like Django.   Really 
thought, I just want to dabble and do some easy stuff.   Does anyone have any 
suggestons?   I have a a website hosted with a hosting company who is supposed 
to have python support but hard to know what they have installed on there 
apache server.   I have seen a few examples out there but not too many.



Take a look at "Popular Non Full-Stack Frameworks" here 
https://wiki.python.org/moin/WebFrameworks


--
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: Dabbling in web development

2015-11-19 Thread Ian Kelly
On Thu, Nov 19, 2015 at 2:53 PM, bSneddon  wrote:
> I know there are a plethora of web frameworks out there for Python and to be 
> serious about website developement I should learn on like Django.   Really 
> thought, I just want to dabble and do some easy stuff.   Does anyone have any 
> suggestons?   I have a a website hosted with a hosting company who is 
> supposed to have python support but hard to know what they have installed on 
> there apache server.   I have seen a few examples out there but not too many.

Flask is a good choice if you're just looking for something easy to get going.
-- 
https://mail.python.org/mailman/listinfo/python-list


Dabbling in web development

2015-11-19 Thread bSneddon
I know there are a plethora of web frameworks out there for Python and to be 
serious about website developement I should learn on like Django.   Really 
thought, I just want to dabble and do some easy stuff.   Does anyone have any 
suggestons?   I have a a website hosted with a hosting company who is supposed 
to have python support but hard to know what they have installed on there 
apache server.   I have seen a few examples out there but not too many.  
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-19 Thread BartC

On 19/11/2015 19:19, Chris Angelico wrote:

On Fri, Nov 20, 2015 at 5:19 AM, BartC  wrote:



But every choice has consequences. Steven gave you a few examples of
the consequences of late-binding default arguments. For example, can
you translate this into (one of) your language(s), and explain the
semantics of the late binding?

# scope 1: can be a module, an inner function, whatever
y = 42
def func(x=y):
 return x
def change_y():
 global y # affect the one in this scope
 y = 28

# scope 2: another module/function/etc
from scope1 import func # gain access, however that's done

change_y()
y = 7
func()


Should this return 7, 28, or 42?


I tried in two languages and both returned 28 the first time. Then I 
realised I'd missed out the y=7 line. Both then printed 7.


It doesn't matter so much if split across modules or not; it depends 
mainly on whether the y in 'y=7' is the same one in 'x=y' and 'y=28' and 
this depends on how it's declared or not and how.


(Both are here if you're interested: http://pastebin.com/0WPrYQw6)

Actually I'm just glad I got one of the results in your list!

(Python returns 42; so that means my languages are more dynamic than 
Python? That's hard to believe!)



 you don't need to look anywhere outside the

function's own definition to grok its defaults. The default is stable
(it won't change from one run to another - it'll always be the same
object). Scope-recognizing late binding would use 28; it re-evaluates
the expression 'y' in its original scope. This one makes the most
sense to me, of all late-bind semantics; it also happens to be the
same semantics as you get if you do the classic "if x is None: x=y"
late-bind in Python, modulo the effect of the nested scope. But you're
saying that it "simply substitute[s] the expression", which would mean
that "func()" is exactly the same as "func(y)". A function default
argument is therefore able to STEAL STUFF FROM THE CALLER'S SCOPE.
Sorry for shouting, but if that ain't bizarre, I don't know what is.


Well, it's not quite the same as textual substitution of the default 
value expression, which would use names in the local scope at the call site.


The expression is evaluated using the entities in scope where the 
function is defined, as far as I can determine, although the byte-code 
that evaluates it is at the call site.


This is necessary I think because you want the default value to 
evaluated to the same result independently of the actual call site 
(unless the caller has deliberately manipulated things as in your example).


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


Re: Late-binding of function defaults (was Re: What is a function parameter =[] for?)

2015-11-19 Thread Marko Rauhamaa
Laura Creighton :

> My experience says that the people who are confused want lists to
> behave like tuples. period. i.e. they don't want lists to be mutable.

I think it's simpler than that. When you have:

   def f(x=[]):
   y = []

the first [] is evaluated when "def" is executed, while the latter [] is
evaluated whenever "f" is executed. It's easy to be confused.


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


Re: Unsuccessful installation

2015-11-19 Thread Ian Kelly
On Thu, Nov 19, 2015 at 12:45 PM, Kaufman, Stan  wrote:
> Python would not run on this Windows XP computer.  After four  attempts at 
> "change/remove" it still gives the same message:
>
> [cid:image001.png@01D122D0.93CC3270]
>
> The first trip through "change/remove" appeared to be a further step in 
> installation.  The second through fourth trips indicated "repairing..."  Each 
> time, an attempt to run it resulted in the above message.

Python 3.5 does not support Windows XP. When Python 3.5.1 is released,
the installer will better communicate this.

You need to upgrade your OS to Vista or more recent, or downgrade your
Python to 3.4.
-- 
https://mail.python.org/mailman/listinfo/python-list


Unsuccessful installation

2015-11-19 Thread Kaufman, Stan
Python would not run on this Windows XP computer.  After four  attempts at 
"change/remove" it still gives the same message:

[cid:image001.png@01D122D0.93CC3270]

The first trip through "change/remove" appeared to be a further step in 
installation.  The second through fourth trips indicated "repairing..."  Each 
time, an attempt to run it resulted in the above message.




---
Stan Kaufman
Principal Scientist (retired)
TSI Incorporated
500 Cardigan Road
St. Paul, MN 55126

---
"Science is what we have learned about how to keep from fooling ourselves."
Richard Feynman
---


This e-mail or the documents accompanying this e-mail contain information that 
may be confidential and/or privileged. 
It may also be prohibited from disclosure under applicable law. The information 
is intended to be for the use of the 
individual or entity named on this transmission. If you are not the intended 
recipient, be aware that any disclosure, 
copying, distribution or use of the contents of this information is without 
authorization and is prohibited. If you 
have received this e-mail in error, please notify us immediately so that we can 
take action to correct the problem.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How can I export data from a website and write the contents to a text file?

2015-11-19 Thread Patrick Hess
ryguy7272 wrote:
> text_file = open("C:/Users/rshuell001/Desktop/excel/Text1.txt", "wb")
> [...]
> It doesn't seem like the '\n' is doing anything useful.  All the text is 
> jumbled together.
> [...]
> I finally got it working.  It's like this:
> "\r\n"

The better solution would be to open text files in actual text mode:

open("filename", "wb")   # binary mode
open("filename", "w")# text mode

In text mode, the correct line-ending characters, which will vary
depending on the operating system, are chosen automatically.

with open("test.txt", "w") as textfile:
textfile.write("line 1\n")
textfile.write("line 2")

This produces "line 1\nline 2" on Unix systems and "line 1\r\nline 2"
on Windows.

Also involves less typing this way. ;-)

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


failing to run python on my pc

2015-11-19 Thread Daniel Kasuza
Dear Sir/Madam
I am student with University of the people and a beginner in programming.
My problem is that l have down loaded python 2.7 but l am failing to muse
it. If l try to to use it, I am getting an option which say run. If l press
run, it just run and come back to the same option. I want to use it for
some practice but i am failing.
Please help
Daniel
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Late-binding of function defaults (was Re: What is a function parameter =[] for?)

2015-11-19 Thread Laura Creighton
In a message of Fri, 20 Nov 2015 06:46:42 +1100, Chris Angelico writes:

>Would this satisfy the people who get confused about "=[]"?
>
>ChrisA

My experience says that the people who are confused want lists to
behave like tuples.  period.  i.e. they don't want lists to be 
mutable.  Which means when I say 'use a tuple instead' they go
away happy. Lots of very occasional programmers in my world (children)
just use tuples instead of lists and never get surprises and 
never go on to learn about lists and why they are a good idea.

But then there are those who come back with the problem:
'my python program is too slow'.  From a perspective of
'Let us understand why this is so and what could we do to make
things faster', I can get them to come up with the idea of a 
python list all on their own.  But this requires the sort of
brain that is interested in how interpreters work, otherwise
this conversation will not happen.

Without the actual problem biting them, the whole idea of
mutable objects seems, ah, hazardous.  I wonder if we do people
a disservice by introducing them straight off in teaching python
to absolute beginners, and if the learning would go easier if
we taught tuples and made them all use them a while before we
gave them lists.

At any rate, 'what is a mutable object' is a conversation that I 
have had too many times with people who really aren't interested.
I now think that 'use a tuple instead' is the way to go, with the
addition -- come back and talk to me about this at any time if you
want to learn why this is so.

Laura

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


Re: What is a function parameter =[] for?

2015-11-19 Thread Chris Angelico
On Fri, Nov 20, 2015 at 6:48 AM, BartC  wrote:
> On 19/11/2015 19:09, Chris Angelico wrote:
>>
>> On Fri, Nov 20, 2015 at 5:50 AM, BartC  wrote:
>>>
>>> But you're not going to tell me what it is I got wrong!
>>>
>>> I said that Python's "=" does a very shallow copy. And I stated that in
>>> A=B,
>>> something of B must be copied into A.
>>>
>>> I (and probably others) would like to know why none of that is correct.
>>> But
>>> I suspect I'm not wrong.
>>
>>
>> There's no copying happening. You evaluate the expression `B`, and get
>> back some kind of object (because all expressions in Python evaluate
>> to objects, unless they raise exceptions or in some way don't finish
>> evaluating). The name A then becomes bound to that object. You're not
>> copying a reference; you're simply referencing the result of an
>> expression.
>
>
> OK, so it's just a coincidence that after A=B, id(A) appears to be an
> identical copy of id(B)? And which also agrees with my assertions that a
> very shallow copy is done, and that some aspect of B is duplicated in A.

When you execute A=B, you start by evaluating the expression B. It's
not a coincidence that re-evaluating a simple name immediately
afterward yields the same object:

>>> id(B)
140330420093056
>>> id(B)
140330420093056
>>> id(B)
140330420093056
>>> id(B)
140330420093056

But that's all you've proven. You've shown that the result of
evaluating B twice was the same object each time. That's no proof of
copying; it's just proof that, barring threading or other reentrancy
problems, expressions consisting solely of simple names are stable.

>> It is an excellent explanation of the exact points you're confused about.
>
>
> As far I'm concerned I'm not confused by these copying aspects. I said 'very
> shallow copy', not 'shallow copy' nor 'deep copy' nor just 'copy'. To me,
> 'very shallow copy' about sums it up.
>
> While Python byte-code for A=B:
>
> 6 LOAD_GLOBAL  0 (b)
> 9 STORE_GLOBAL 1 (a)

Technically that's CPython byte code. Python (the language) specifies
the semantics of assignment, but not the exact byte code used.

> doesn't really disagree with me either as it looks remarkably like any other
> basic copy operation of any machine language or byte-code that has ever been
> invented.

I think you're warping the word "copy" to mean what Python does on
assignment, rather than noting an actual similarity between Python
assignment and any other concept of copying. Remember, Python does not
have pointers, in the sense of machine integers storing addresses.
When you assign one C pointer variable to another, yes, you're copying
that integer value; but Python doesn't work that way, so there is
nothing to copy.

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


Re: What is a function parameter =[] for?

2015-11-19 Thread BartC

On 19/11/2015 19:09, Chris Angelico wrote:

On Fri, Nov 20, 2015 at 5:50 AM, BartC  wrote:

But you're not going to tell me what it is I got wrong!

I said that Python's "=" does a very shallow copy. And I stated that in A=B,
something of B must be copied into A.

I (and probably others) would like to know why none of that is correct. But
I suspect I'm not wrong.


There's no copying happening. You evaluate the expression `B`, and get
back some kind of object (because all expressions in Python evaluate
to objects, unless they raise exceptions or in some way don't finish
evaluating). The name A then becomes bound to that object. You're not
copying a reference; you're simply referencing the result of an
expression.


OK, so it's just a coincidence that after A=B, id(A) appears to be an 
identical copy of id(B)? And which also agrees with my assertions that a 
very shallow copy is done, and that some aspect of B is duplicated in A.



It is an excellent explanation of the exact points you're confused about.


As far I'm concerned I'm not confused by these copying aspects. I said 
'very shallow copy', not 'shallow copy' nor 'deep copy' nor just 'copy'. 
To me, 'very shallow copy' about sums it up.


While Python byte-code for A=B:

6 LOAD_GLOBAL  0 (b)
9 STORE_GLOBAL 1 (a)

doesn't really disagree with me either as it looks remarkably like any 
other basic copy operation of any machine language or byte-code that has 
ever been invented.


If you said instead that I'm not using the official jargon then perhaps 
you're right. But the right terminology isn't going to make me like 
Python's default values any better!


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


Late-binding of function defaults (was Re: What is a function parameter =[] for?)

2015-11-19 Thread Chris Angelico
On Fri, Nov 20, 2015 at 5:42 AM, Ian Kelly  wrote:
> BartC on the other hand is just complaining about an aspect of Python
> that is legitimately controversial.

IMO it's controversial mainly because there's an easy and obvious
syntax for early binding, but late binding doesn't have syntactic
support, and all the options are imperfect. Consider:

def late1(x=None):
"""Terse but buggy"""
do_stuff_with(x or [])

def late2(x=None):
"""Not bad but has an extra line for each default. Also, can't take None."""
if x is None: x = []
do_stuff_with(x)

_SENTINEL = object()
def late3(x=_SENTINEL):
"""Has the same global-pollution problem you get when you
try to construct early binding from late; you can share the
sentinel among multiple args, even multiple funcs, though"""
if x is _SENTINEL: x = []
do_stuff_with(x)

def late4(x=object()):
"""Depends on its own name remaining bound in its scope,
and will break if you change argument order"""
if x is late4.__defaults__[0]: x = []
do_stuff_with(x)

And there might be other techniques, too. They all share one important
flaw, too: When you ask for help about the function, you can't see
what the default really is. All you see is:

late1(x=None)
late3(x=)

In the first two cases, it's not too bad; you can specify a timeout as
either a number or as None, and if it's None (the default), the
timeout is three times the currently estimated round trip time. No
problem. But how would you implement something like next() in pure
Python? If you provide _any second argument at all_, it returns that
instead of raising StopIteration. The ONLY way that I can think of is
to use *args notation:

def next(iterator, *default):
try:
return iterator.__next__()
except StopIteration:
if default: return default[0]
raise

And while that isn't TOO bad for just one argument, it scales poorly:

def foo(fixed_arg, *args):
"""Foo the fixed_arg against the spam mapping, the
ham sequence, and the jam file."""
args.reverse()
spam = args.pop() if args else {}
ham = args.pop() if args else []
jam = args.pop() if args else open("jam.txt")

Suppose, instead, that Python had a syntax like this:

def foo(fixed_arg, spam=>{}, ham=>[], jam=>open("jam.txt")):
"""Foo the fixed_arg against the spam mapping, the
ham sequence, and the jam file."""

The expressions would be evaluated as closures, using the same scope
that the function's own definition used. (This won't keep things alive
unnecessarily, as the function's body will be nested within that same
scope anyway.) Bikeshed the syntax all you like, but this would be
something to point people to: "here's how to get late-binding
semantics". For the purposes of documentation, the exact text of the
parameter definition could be retained, and like docstrings, they
could be discarded in -OO mode.

Would this satisfy the people who get confused about "=[]"?

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


Re: What is a function parameter =[] for?

2015-11-19 Thread Ian Kelly
On Thu, Nov 19, 2015 at 12:19 PM, Chris Angelico  wrote:
> But you're
> saying that it "simply substitute[s] the expression", which would mean
> that "func()" is exactly the same as "func(y)". A function default
> argument is therefore able to STEAL STUFF FROM THE CALLER'S SCOPE.
> Sorry for shouting, but if that ain't bizarre, I don't know what is.

It's like pass-by-name, but in reverse.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-19 Thread Chris Angelico
On Fri, Nov 20, 2015 at 5:19 AM, BartC  wrote:
> Yes. In the languages I create, pretty much everything is mutable, provided
> it can supply an l-value. Constructs such as those for empty lists ([] in
> Python, () in mine) aren't l-values.
>
> But it doesn't apply default values. The language is very different however,
> because the byte-code compiler always has full knowledge of functions that
> are called directly. Then it knows when an argument is omitted, and can
> simply substitute the expression used as the default.

In other words, your language uses late binding by default. That's
fine; it's a design choice that you've made one way and Python's made
the other way. It's on par with design choices like whether adding a
string and an integer implicitly stringifies the int, or raises an
error. I know several good languages that have taken each of those
choices.

But every choice has consequences. Steven gave you a few examples of
the consequences of late-binding default arguments. For example, can
you translate this into (one of) your language(s), and explain the
semantics of the late binding?

# scope 1: can be a module, an inner function, whatever
y = 42
def func(x=y):
return x
def change_y():
global y # affect the one in this scope
y = 28

# scope 2: another module/function/etc
from scope1 import func # gain access, however that's done

change_y()
y = 7
func()


Should this return 7, 28, or 42? Early binding demands 42, which is
nice and simple: you don't need to look anywhere outside the
function's own definition to grok its defaults. The default is stable
(it won't change from one run to another - it'll always be the same
object). Scope-recognizing late binding would use 28; it re-evaluates
the expression 'y' in its original scope. This one makes the most
sense to me, of all late-bind semantics; it also happens to be the
same semantics as you get if you do the classic "if x is None: x=y"
late-bind in Python, modulo the effect of the nested scope. But you're
saying that it "simply substitute[s] the expression", which would mean
that "func()" is exactly the same as "func(y)". A function default
argument is therefore able to STEAL STUFF FROM THE CALLER'S SCOPE.
Sorry for shouting, but if that ain't bizarre, I don't know what is.

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


Re: What is a function parameter =[] for?

2015-11-19 Thread Chris Angelico
On Fri, Nov 20, 2015 at 5:50 AM, BartC  wrote:
> But you're not going to tell me what it is I got wrong!
>
> I said that Python's "=" does a very shallow copy. And I stated that in A=B,
> something of B must be copied into A.
>
> I (and probably others) would like to know why none of that is correct. But
> I suspect I'm not wrong.

There's no copying happening. You evaluate the expression `B`, and get
back some kind of object (because all expressions in Python evaluate
to objects, unless they raise exceptions or in some way don't finish
evaluating). The name A then becomes bound to that object. You're not
copying a reference; you're simply referencing the result of an
expression.

PLEASE finish reading Ned's talk. Here's the link again:

http://nedbatchelder.com/text/names1.html

It is an excellent explanation of the exact points you're confused about.

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


Re: What is a function parameter =[] for?

2015-11-19 Thread BartC

On 19/11/2015 18:26, Mark Lawrence wrote:

On 19/11/2015 18:19, BartC wrote:



if you write A=B then something of B needs to have been copied into
A, even if it's just the reference that B contains. Otherwise it
would be
difficult to get A to refer to the same object as B.


Please, PLEASE, go and read/watch Ned's PyCon talk (the one I linked
you to earlier). Don't post another word on this subject until you
comprehend what he is saying.





But what is it about my remarks above that isn't right?




To summarize, it once again shows that you haven't got the faintest idea
what you're talking about.


But you're not going to tell me what it is I got wrong!

I said that Python's "=" does a very shallow copy. And I stated that in 
A=B, something of B must be copied into A.


I (and probably others) would like to know why none of that is correct. 
But I suspect I'm not wrong.



--
Bartc


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


Re: What is a function parameter =[] for?

2015-11-19 Thread Oscar Benjamin
On 19 November 2015 at 18:19, BartC  wrote:
>>>
>>> if you write A=B then something of B needs to have been copied into
>>> A, even if it's just the reference that B contains. Otherwise it would be
>>> difficult to get A to refer to the same object as B.
>>
>> Please, PLEASE, go and read/watch Ned's PyCon talk (the one I linked
>> you to earlier). Don't post another word on this subject until you
>> comprehend what he is saying.
>
> I looked through the long article (I don't remember seeing a link to a
> video), and followed it up to about 3/4 of the way through, then it got a
> bit heavy.
>
> But what is it about my remarks above that isn't right?

It's not necessarily incorrect (just focussing on the remark quoted
above) but you'll find it easier to understand the model if you adopt
the same terminology that is usually used. When talking of "copying"
in a Python context something different is implied than what happens
with A=B.

The statement A=B (assuming A and B are names and not expressions)
simply binds the name A to the same object that the name B is bound
to. In the implementation of CPython the names are associated with
pointers and the value of the pointer associated with B is copied to
the pointer associated with A. Another implementation may not use
pointers but there will in some way be a "reference" that is "copied"
over if you like to view it that way.

However in a Python context when someone talks of "copying" they will
mean something different: creating a new object which is distinct
from, but has the same value as, some previously existing object. It
is important in Python to distinguish between operations that
create/mutate objects and operations that rebind names. This
distinction has semantic implications that are not hard to understand
if you think about them carefully and consistent use of terminology
really helps.

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


Re: What is a function parameter =[] for?

2015-11-19 Thread Ian Kelly
On Thu, Nov 19, 2015 at 11:26 AM, Mark Lawrence  wrote:
> To summarize, it once again shows that you haven't got the faintest idea
> what you're talking about.  You're now in a very exclusive club with the RUE
> and Nick the Greek, the world's leading webmaster.

Eh. Ranting Rick and Mark Janssen / Zipher / TheDoctor / whatever name
he's using now belong in that club, but Nikos was just incompetent,
not a crackpot.

BartC on the other hand is just complaining about an aspect of Python
that is legitimately controversial.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-19 Thread Marko Rauhamaa
BartC :

> Yes. In the languages I create, pretty much everything is mutable,
> provided it can supply an l-value. Constructs such as those for empty
> lists ([] in Python, () in mine) aren't l-values.
>
> But it doesn't apply default values.

Python's default-value semantics is analogous to C++:


#include 

using namespace std;

static int z;

static void f(int &x = z)
{
x++;
}

int main()
{
cout << z << endl;
f();
cout << z << endl;
f();
cout << z << endl;
return 0;
}


which prints:

0
1
2


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


Re: What is a function parameter =[] for?

2015-11-19 Thread Mark Lawrence

On 19/11/2015 18:19, BartC wrote:

On 19/11/2015 17:45, Chris Angelico wrote:

On Fri, Nov 20, 2015 at 4:30 AM, BartC  wrote:

The whole concept of 'mutable' default is alien to me. A default is
just a
convenient device to avoid having to write:

   fn(0) or fn("") or fn([])

You just write fn() instead. But it shouldn't come at the cost of
completely
different semantics! Because then it can't really be called a default
value
at all.



Do you understand the concept of "mutable objects"? Don't even try to
discuss mutable function defaults until you do.


Yes. In the languages I create, pretty much everything is mutable,
provided it can supply an l-value. Constructs such as those for empty
lists ([] in Python, () in mine) aren't l-values.

But it doesn't apply default values. The language is very different
however, because the byte-code compiler always has full knowledge of
functions that are called directly. Then it knows when an argument is
omitted, and can simply substitute the expression used as the default.


If your language simply has no mutable objects, then sure, it's easy
to understand function defaults! There's no such thing as early or
late binding; in fact, you can even super-late-bind, where you don't
actually call a function until its *return value* is being used (as
long as that function has no side effects). But as soon as objects are
capable of retaining their identities while changing their values, you
need an object model that (a) distinguishes between identity and
value, and (b) allows some definition of early or late binding,
because it *will* matter.


if you write A=B then something of B needs to have been copied into
A, even if it's just the reference that B contains. Otherwise it
would be
difficult to get A to refer to the same object as B.


Please, PLEASE, go and read/watch Ned's PyCon talk (the one I linked
you to earlier). Don't post another word on this subject until you
comprehend what he is saying.


I looked through the long article (I don't remember seeing a link to a
video), and followed it up to about 3/4 of the way through, then it got
a bit heavy.

But what is it about my remarks above that isn't right?



To summarize, it once again shows that you haven't got the faintest idea 
what you're talking about.  You're now in a very exclusive club with the 
RUE and Nick the Greek, the world's leading webmaster.


--
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: What is a function parameter =[] for?

2015-11-19 Thread Mark Lawrence

On 19/11/2015 17:30, BartC wrote:

On 19/11/2015 16:01, Steven D'Aprano wrote:

On Fri, 20 Nov 2015 12:19 am, BartC wrote:



You know, for somebody who claims to design and implement your own
languages, you sometimes go to a remarkable effort to claim to be a
dummy.
You write your own interpreter, but can't understand early versus late
binding? I don't think so.


No I don't; so? Maybe my interpreter can do its thing without being
aware that what it's doing has been called 'late binding' or 'early
binding' by someone else.

At least its default values work as expected!



Python's default values work exactly as I expect as the subject has been 
debated at least twice a year on c.l.py for the 15 or so years that I've 
been using Python.  If your expectations are clearly wrong, that is your 
problem and your problem alone.  A solution to your problem is another 
language that does meet all of your expectations, but as there is never 
a "one size fits all" the only one that I can think of is your own, 
whatever that is called.


--
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: What is a function parameter =[] for?

2015-11-19 Thread BartC

On 19/11/2015 17:45, Chris Angelico wrote:

On Fri, Nov 20, 2015 at 4:30 AM, BartC  wrote:

The whole concept of 'mutable' default is alien to me. A default is just a
convenient device to avoid having to write:

   fn(0) or fn("") or fn([])

You just write fn() instead. But it shouldn't come at the cost of completely
different semantics! Because then it can't really be called a default value
at all.



Do you understand the concept of "mutable objects"? Don't even try to
discuss mutable function defaults until you do.


Yes. In the languages I create, pretty much everything is mutable, 
provided it can supply an l-value. Constructs such as those for empty 
lists ([] in Python, () in mine) aren't l-values.


But it doesn't apply default values. The language is very different 
however, because the byte-code compiler always has full knowledge of 
functions that are called directly. Then it knows when an argument is 
omitted, and can simply substitute the expression used as the default.



If your language simply has no mutable objects, then sure, it's easy
to understand function defaults! There's no such thing as early or
late binding; in fact, you can even super-late-bind, where you don't
actually call a function until its *return value* is being used (as
long as that function has no side effects). But as soon as objects are
capable of retaining their identities while changing their values, you
need an object model that (a) distinguishes between identity and
value, and (b) allows some definition of early or late binding,
because it *will* matter.


if you write A=B then something of B needs to have been copied into
A, even if it's just the reference that B contains. Otherwise it would be
difficult to get A to refer to the same object as B.


Please, PLEASE, go and read/watch Ned's PyCon talk (the one I linked
you to earlier). Don't post another word on this subject until you
comprehend what he is saying.


I looked through the long article (I don't remember seeing a link to a 
video), and followed it up to about 3/4 of the way through, then it got 
a bit heavy.


But what is it about my remarks above that isn't right?

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


Re: Why doesn't this method have access to its "self" argument?

2015-11-19 Thread Peter Otten
Robert Latest via Python-list wrote:

> I found a workaround using a wrapper method which calls a C function,
> passing the instance as a separate argument. It works, and I cannot see
> any disadvantage. It's just not as elegant as I'd like it to be, and I
> don't understand WHY the C "method" doesn't receive a pointer to the
> Python instance. Maybe somebody can clarify.

I don't know much about the C-implementation side, but functions written in 
Python are also descriptors. Given

def f(self): pass

class A(object):
m = f
c = abs
v = 42

a = A()

a seemingly simple attribute access

m = a.m  # m is now a bound method

invokes f.__get__(a, A) under the hood while

m = a.c
assert m is abs

just returns the function (abs in the example) the same way it returns any 
other value:

v = a.v
assert v == 42


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


Re: What is a function parameter =[] for?

2015-11-19 Thread Chris Angelico
On Fri, Nov 20, 2015 at 4:30 AM, BartC  wrote:
> The whole concept of 'mutable' default is alien to me. A default is just a
> convenient device to avoid having to write:
>
>   fn(0) or fn("") or fn([])
>
> You just write fn() instead. But it shouldn't come at the cost of completely
> different semantics! Because then it can't really be called a default value
> at all.
>

Do you understand the concept of "mutable objects"? Don't even try to
discuss mutable function defaults until you do.

If your language simply has no mutable objects, then sure, it's easy
to understand function defaults! There's no such thing as early or
late binding; in fact, you can even super-late-bind, where you don't
actually call a function until its *return value* is being used (as
long as that function has no side effects). But as soon as objects are
capable of retaining their identities while changing their values, you
need an object model that (a) distinguishes between identity and
value, and (b) allows some definition of early or late binding,
because it *will* matter.

> if you write A=B then something of B needs to have been copied into
> A, even if it's just the reference that B contains. Otherwise it would be
> difficult to get A to refer to the same object as B.

Please, PLEASE, go and read/watch Ned's PyCon talk (the one I linked
you to earlier). Don't post another word on this subject until you
comprehend what he is saying.

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


Re: Why doesn't this method have access to its "self" argument?

2015-11-19 Thread Chris Angelico
On Fri, Nov 20, 2015 at 3:13 AM, Robert Latest via Python-list
 wrote:
> rl@dc:~/c/cwsf/python_module$ python test.py
>
> Minimal example files:
>
> == test.py ===
>
> import cmethod
>
> class Test():
>
> # add methods to the class "after the fact"
> Test.py_method = py_method
> Test.c_method = cmethod.c_method

Are you using Python 2 here? If so, you're using an old-style class,
which has specific consequences that I can never remember. Does the
situation change if you slap 'object' between those parentheses? Or if
you use Python 3?

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


Re: What is a function parameter =[] for?

2015-11-19 Thread BartC

On 19/11/2015 16:01, Steven D'Aprano wrote:

On Fri, 20 Nov 2015 12:19 am, BartC wrote:



You know, for somebody who claims to design and implement your own
languages, you sometimes go to a remarkable effort to claim to be a dummy.
You write your own interpreter, but can't understand early versus late
binding? I don't think so.


No I don't; so? Maybe my interpreter can do its thing without being 
aware that what it's doing has been called 'late binding' or 'early 
binding' by someone else.


At least its default values work as expected! (And they can also be 
applied to existing external functions. Even C API functions where the 
implementation doesn't support these features.


So if an argument is missing, it applies the default I specify in its 
place. It's that simple.)



I understand that the simplest things can be perplexing if you look at them
the wrong way. But we've explained multiply times now, or at least tried to
explain, that the argument default is a single object. That is blindingly
obvious once you look at it the right way, and it is a nice, clean design.


I can understand now how it works as it does. But I still think it is 
unintuitive. A language design could have chosen to make it work however 
it liked.



There's no need to introduce extra modes where code has to be stored away
to be evaluated later (apart from the body of the function itself).
Everything works the same way: assignment always evaluates a result and
binds it to the name, whether that assignment is in a parameter list or
not.

If you insist on thinking about it in terms of how C or Pascal work, of
course you will confuse yourself. The argument default is evaluated when
the function is created, and the resulting object is stored away for later
use, inside the function. That is clean and easy to understand.

I'm not saying that the behaviour with mutable defaults


The whole concept of 'mutable' default is alien to me. A default is just 
a convenient device to avoid having to write:


  fn(0) or fn("") or fn([])

You just write fn() instead. But it shouldn't come at the cost of 
completely different semantics! Because then it can't really be called a 
default value at all.


 isn't surprising to

somebody coming from a completely different paradigm. I was surprised by it
too, the first time I got bitten.


So you didn't bother reading the LRM either!


py> def demo_const(x, y=[]):
... return x + len(y)



Exactly as you should expect. Where you run into trouble is when the default
value is NOT a constant:

py> def demo_variable(x, y=[]):
... y.append(1)
... return x + len(y)


Sorry, what is the default value in each of these? As the first lines of 
the defintions look identical apart from the function names.



...
py> demo_variable(5)
6
py> demo_variable(5)
7
py> demo_variable(5)
8


If you modify the value, the value will be modified. Why are you surprised
by this?


Which value is being modified? The []?


And most often that constant is 0, "" or an empty list.

You want these very common examples to /just work/ instead of going to
lengths trying to explain why they don't.


Ah, the good-old "I shouldn't have to think to understand programming" model
of programming. Because that works so well.


It works well when sharing code because not everyone understands things 
at the same level.



Maybe you can wrap the entire module inside a function? Other than a bit
at the end that calls that function. Does that solve the global lookup
problem?


No.


Why not?




When you deal with mutable objects, you have to expect them to mutate.
The whole point of mutability is that their value can change.


That [] doesn't look like an object that could change.


Of course it does.


You've lost me know.

Are you saying that:

  a=[]

why sometimes not assign an empty list, because that [] could have been 
modified?


It is a list literal, like int literals, float literals,

string literals and the rest.


Another surprise? Literals by definition can't change:

def fn():
a=[10,20,30]
a.append(999)

I would hope that a is set to [10,20,30] at each entry to the function!


You presumably think differently because you have some inside knowledge
of how Python works, and know that that [] undergoes a one-time
assignment to a local, persistent 'default' variable where it's value
can indeed by changed. (Thanks to another Python feature where an
assignment is a very shallow copy of an object.) And it is that volatile
variable that is the actual default.


Assignments are not copies at all.


if you write A=B then something of B needs to have been copied into A, 
even if it's just the reference that B contains. Otherwise it would be 
difficult to get A to refer to the same object as B.


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


Re: What is a function parameter =[] for?

2015-11-19 Thread Chris Angelico
On Fri, Nov 20, 2015 at 3:01 AM, Steven D'Aprano  wrote:
> You know, for somebody who claims to design and implement your own
> languages, you sometimes go to a remarkable effort to claim to be a dummy.
> You write your own interpreter, but can't understand early versus late
> binding? I don't think so.

I'm not sure that's such a fair comparison. Anyone can design a
brand-new language, and even implementing one isn't all that hard. If
you don't understand other languages, you can certainly create the one
that always does what you think most intuitive, right at the instant
when you designed/implemented some feature. What's hard is designing a
clean language that does what _someone else_ expects. (And that
includes yourself in six months.)

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


Re: Writing a Financial Services App in Python

2015-11-19 Thread Michael Torrie
On 11/19/2015 09:20 AM, Cai Gengyang wrote:
> Sure ... is this : https://www.codecademy.com/learn/python a good
> place to learn Python ?

Why not have a look first at the many tutorials, including the ones on
Python's web site?  You need to explore feasibility first before you go
too far. Python is not the only language out there. I happen to like it,
but there are other popular choices.  An experienced developer can pick
up and program in any language very quickly.

Also you need to know a lot more than just programming in Python.  You
will need to know the various web development technologies and languages.

I don't say this just to discourage you up front.  I say this from a lot
of sad experience.  Your goals are *very* ambitious.  I've seen fairly
straightforward web apps stretch out into years and many tens of
thousands of dollars with whole teams of programmers.  And it does not
appear you have any programming experience at all yet.

Forget about a web app for now.  Work on the pieces like the algorithms
needed for doing the analysis you require.  Do some simple programs that
only do console input and output.

> Are you wanting to contract with some programmers to create this
> application for you?  Eventually I will have to find programming
> co-founders and employees to create and iterate the product as user
> feedback streams in. But I will write the initial prototype myself
> because I plan to be the main programmer / founder , but yes ...
> eventually I will need 1 or even 2 co-founders and when the platform
> gains enough users, we will have to hire programmers and sales/
> business people. But this will be a tech-heavy company and all the
> main founders and employees should be excellent programmers. But for
> the moment, I plan to write the initial prototype myself ...

Sounds ambitious! Hope you have a business plan in mind from the start.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: non-blocking getkey?

2015-11-19 Thread Michael Torrie
On 11/19/2015 08:48 AM, Ulli Horlacher wrote:
> 
> The focus is moved to another, unrelated window, but not back to the
> window in which the python scripts run. 
> Same behaviour on Linux (XFCE) and windows 7.

That's because an app that communicates with standard in and standard
out could be running over telnet, theoretically, so there would be no
window at all. There's absolutely no link in stdin and stdout to a
graphical window.  It's not even possible on Windows as the console
subsystem is completely separate from the GUI subsystem.  When your app
opens a Tk window, it's creating a brand new, top-level window, not
associated with any existing window.

One windows it might be possible to use the win32 api to enumerate the
windows, find your console window and switch to it.   Might even be
possible on Linux using raw X11 calls.







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


Re: Is there an meaning of '[[]]' in a list?

2015-11-19 Thread Mark Lawrence

On 19/11/2015 11:28, fl wrote:

Hi,
In the previous exercises, I see list:
cc=[[],[],[]]

Then, I can have this:

ccc=[[[]],[[]],[[]]]

I can also have

ccc[0]
Out[158]: [[]]

ccc[0]='o'

ccc
Out[163]: ['o', [[]], [[]]]


I have question: Is there any difference between [[]] and []?
[[]] can have deeper assignment and use than

ccc[0]='o'


Thanks,



I have question.  Is there any chance that you stop wasting the time of 
people on this list by either doing your own research or trying things 
at an interactive prompt?  Or are you now well past that point, as 
you're learned that the extremely generous people here have fitted your 
bibs, spoon fed you and and changed your nappies so many times that it 
has rendered you incapable of doing anything for yourself?


--
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: Writing a Financial Services App in Python

2015-11-19 Thread Cai Gengyang
Sure ... is this : https://www.codecademy.com/learn/python a good place to 
learn Python ?

Are you wanting to contract with some programmers to create this application 
for you?  Eventually I will have to find programming co-founders and 
employees to create and iterate the product as user feedback streams in. But I 
will write the initial prototype myself because I plan to be the main 
programmer / founder , but yes ... eventually I will need 1 or even 2 
co-founders and when the platform gains enough users, we will have to hire 
programmers and sales/ business people. But this will be a tech-heavy company 
and all the main founders and employees should be excellent programmers. But 
for the moment, I plan to write the initial prototype myself ... 


On Friday, November 20, 2015 at 12:00:34 AM UTC+8, Michael Torrie wrote:
> On 11/19/2015 04:59 AM, Cai Gengyang wrote:
> > 
> > From YCombinator's new RFS, This is the problem I want to solve as it
> > is a severe problem I face myself and something I need. I want to
> > write this app in Python as I heard that Python is a great language
> > that many programmers use ... How / where do I start ? The problem is
> > detailed below :
> 
> I'm afraid you're going to be discouraged.
> 
> Well the first step is you have to learn programming.  And you don't
> start with such a large problem, I assure you.  You start by learning
> the language by following the tutorials, writing small programs to
> become familiar with programming and the language itself.  Then you
> become familiar with related things like algorithms and data structures,
> and how to use them with and from Python (or any language).  Eventually
> you add to that graphical user interface development.
> 
> After that then you might be in a position to start thinking about how
> to design and build a program that does what you were talking about.
> 
> There honestly are no shortcuts.  Python is a great language, and is
> easy to learn, but it's not like you can start cranking out full-blown
> applications magically.  In the hands of experienced programmers, yes
> Python is incredibly fast and flexible for cranking out working apps.
> 
> You might try checking out a Python application development framework
> that can produce apps that will run on Android and iOS (and Windows and
> Linux) called Kivy.  I would think mobile should be your target platform
> for such an app.
> 
> > 
> 
> > This seems to us like something software should help solve. We'd like
> > to see teams tackling each of the component issues around saving and
> > investing, along with ones tackling the entire package.
> 
> Are you wanting to contract with some programmers to create this
> application for you?
-- 
https://mail.python.org/mailman/listinfo/python-list


Why doesn't this method have access to its "self" argument?

2015-11-19 Thread Robert Latest via Python-list
Hi all,

I'm still trying to find a simple way to implement a method (but not the
full class) in C. Suggestions I have recived so far are good, but seem to be
over the top for such a (seemingly) simple problem. I came up with the idea
of implementing the class in Python, and just setting the method after the
actual class definition. See example below. The "py_method" is added to the
class later on, and it seems to become a proper method of the class (and its
instances) just as if it had been defined inside the class itself. Of course
it also has access to its "self" argument.

If I do the same thing with a method implemented in the external module
"cmethod", and I call that method on an instance, it gets passed a NULL
pointer as its "self" argument and so has no access to the instance's "data"
attribute.

I found a workaround using a wrapper method which calls a C function,
passing the instance as a separate argument. It works, and I cannot see any
disadvantage. It's just not as elegant as I'd like it to be, and I don't
understand WHY the C "method" doesn't receive a pointer to the Python
instance. Maybe somebody can clarify.


Here's what happens when I build, install and run the minimal example below:

rl@dc:~/c/cwsf/python_module$ python test.py
py_method(): <__main__.Test instance at 0xb71f5a2c>
c_method(): self at (nil)
c_function(): self at (nil), instance at 0xb71f5a2c
<__main__.Test instance at 0xb71f5a2c>
'Some data'
c_function(): self at (nil), instance at 0xb71f5a2c
<__main__.Test instance at 0xb71f5a2c>
'New Data'
rl@dc:~/c/cwsf/python_module$

Minimal example files:


== test.py ===

import cmethod

class Test():
def __init__(self):
self.data = "Some data"

def wrapper(self):
return cmethod.c_function(self)

def py_method(self):
print "py_method(): %s" % repr(self)

# add methods to the class "after the fact"
Test.py_method = py_method
Test.c_method = cmethod.c_method

foo = Test()
foo.py_method() # works as expected
foo.c_method()  # is passed NULL in its self argument, why?
foo.wrapper()   # works fine, updates "data" attribute
foo.wrapper()   # works fine, sees updated "data" attribute

 cmethod.c ===

#include 
#include 

static PyObject *c_method(PyObject *self, PyObject *args) {
(void) args; /* not used */
fprintf(stderr, "c_method(): self at %p\n",
(void*) self); /* always prints 0x0 */
Py_INCREF(Py_None);
return Py_None;
}

static PyObject *c_function(PyObject *self, PyObject *args) {
PyObject *instance;
PyObject *o;
/* Retrieve instance from wrapper through argument tuple: WORKS */
PyArg_UnpackTuple(args, "c_function", 1, 1, &instance);
fprintf(stderr, "c_function(): self at %p, instance at %p\n",
(void*) self, (void*) instance);
PyObject_Print(instance, stderr, 0); fputc('\n', stderr);
/* Get and set attributes of instance: WORKS */
o = PyObject_GetAttrString(instance, "data");
PyObject_Print(o, stderr, 0); fputc('\n', stderr);
PyObject_SetAttrString(instance, "data",
PyString_FromString("New Data"));
/* Side question: Do I have to DECREF "o"? */
Py_INCREF(Py_None);
return Py_None;
}

static PyMethodDef methods[] =
{
 {"c_method", c_method, METH_VARARGS, "I want to be a class method"},
 {"c_function", c_function, METH_VARARGS, "I am a function"},
 {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initcmethod(void)
{
 (void) Py_InitModule("cmethod", methods);
}


 setup_cmethod.py ===

from distutils.core import setup, Extension

module1 = Extension('cmethod', sources = ['cmethod.c'])

setup (name = 'cmethod',
version = '0.1',
description = 'struggling to implement a class method in C',
ext_modules = [module1])


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


Re: Writing a Financial Services App in Python

2015-11-19 Thread Michael Torrie
On 11/19/2015 08:24 AM, Cai Gengyang wrote:
> It will be a web-based application.

Contract it out.  Or attract people who are interested in making an open
source application.  What you are thinking of is a massive undertaking.

Web-based application design is even more complicated than desktop app
design.  Web development involves many different languages.  Requires a
working knowledge of:

- Python programming
- a web framework for processing events like Django or web2py or
something similar
- html
- css
- SQL
- Javascript, including jquery and probably others

To say nothing of the algorithms necessary to implement the trend
analysis you speak of.

> I for example, am a terrible trader because of having almost zero 
> discipline and thus keep losing money.

Something tells me if the people you're trying to help have zero
discipline, then I don't think software is really going to help them.
Computers are just tools.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-19 Thread Steven D'Aprano
On Fri, 20 Nov 2015 12:19 am, BartC wrote:

> On 19/11/2015 12:19, Steven D'Aprano wrote:
>> On Thu, 19 Nov 2015 10:14 am, BartC wrote:
> 
>> Consider this pair of functions:
>>
>>
>> def expensive():
>>  # Simulate some expensive calculation or procedure.
>>  time.sleep(100)
>>  return random.randint(1, 6)
>>
>>
>> def demo(arg=expensive()):
>>  return arg + 1
[...]
> If someone /wants/ expensive() to be called each time, then why not? If
> they don't, then it seems easy enough to write:
> 
> demo_default=expensive()
> def demo(arg=demo_default):
> ...
> 
> (As you mention later...)

Yes, I mentioned it, and you seem to have failed to understand why that is a
horrible solution that causes more problems than it solves.

It breaks encapsulation -- data which belongs to the function has to be
stored outside the function, in a global variable, where just anybody or
anything could come along and modify it or delete it. It pollutes the
namespace -- imagine a module with twenty functions, each function having
four or five arguments that take default values. That's 80 to 100 global
variables, which all need to have unique names.

Yuck.


>> - if the language defaults to early binding, it is *easy* for the
>>programmer to get late binding semantics;
>>
>> - if the language defaults to late binding, it is *very difficult*
>>for the programmer to get early binding semantics.
> 
> I got the impression that Python was a nice, easy language for everyone
> to use. Not one where you need a Master's degree in CS to understand the
> nuances of! And to understand why something that is so blindingly
> obvious doesn't work.

Master's degree in CS, ha ha very funny. Not.

You know, for somebody who claims to design and implement your own
languages, you sometimes go to a remarkable effort to claim to be a dummy.
You write your own interpreter, but can't understand early versus late
binding? I don't think so.

I understand that the simplest things can be perplexing if you look at them
the wrong way. But we've explained multiply times now, or at least tried to
explain, that the argument default is a single object. That is blindingly
obvious once you look at it the right way, and it is a nice, clean design.
There's no need to introduce extra modes where code has to be stored away
to be evaluated later (apart from the body of the function itself).
Everything works the same way: assignment always evaluates a result and
binds it to the name, whether that assignment is in a parameter list or
not.

If you insist on thinking about it in terms of how C or Pascal work, of
course you will confuse yourself. The argument default is evaluated when
the function is created, and the resulting object is stored away for later
use, inside the function. That is clean and easy to understand.

I'm not saying that the behaviour with mutable defaults isn't surprising to
somebody coming from a completely different paradigm. I was surprised by it
too, the first time I got bitten. But surprising doesn't equal *wrong*. The
reason it was surprising to me was because I didn't think through the
implications of what I already knew. I knew the default value was
calculated once. I knew that the list was mutable. But I never put 2 and 2
together to get 4.

If you have a list which is created once, and modify it, the second time you
use it, it will be modified. Well duh. In hindsight, I shouldn't have been
surprised. The fact that I was is *my* failure.

It might be surprising the *first* time you see it, because you failed to
think it through. If you modify the object, *naturally* it will be
modified. Or if you failed to understand that the object was created once
and once only.

The interesting thing is, I've seen people write code *in the same program*
which assumed early binding in one function and late binding in another.
*Whichever* choice Python made, their program would have broken in one
place or the other. I don't believe that people have an inherent
expectation of one or the other. I believe that people expect whichever is
more convenient for them at the time, and get disappointed when it doesn't
work.


>> But let's try going the other way. Suppose function defaults were
>> evaluated each and every time you called the function. How could you
>> *avoid* the expense and waste of re-evaluating the default over and over
>> again?
> 
> I use default parameters a lot in other languages.
> 
> 99% of the time the default value is a constant.

Well, if it's a constant, then (apart from efficiency) early binding and
late binding makes *absolutely no difference*. Watch:


py> def demo_const(x, y=[]):
... return x + len(y)
...
py> demo_const(5)
5
py> demo_const(5)
5

Exactly as you should expect. Where you run into trouble is when the default
value is NOT a constant:

py> def demo_variable(x, y=[]):
... y.append(1)
... return x + len(y)
...
py> demo_variable(5)
6
py> demo_variable(5)
7
py> demo_variable(5)
8


If you modify the v

Re: Writing a Financial Services App in Python

2015-11-19 Thread Michael Torrie
On 11/19/2015 04:59 AM, Cai Gengyang wrote:
> 
> From YCombinator's new RFS, This is the problem I want to solve as it
> is a severe problem I face myself and something I need. I want to
> write this app in Python as I heard that Python is a great language
> that many programmers use ... How / where do I start ? The problem is
> detailed below :

I'm afraid you're going to be discouraged.

Well the first step is you have to learn programming.  And you don't
start with such a large problem, I assure you.  You start by learning
the language by following the tutorials, writing small programs to
become familiar with programming and the language itself.  Then you
become familiar with related things like algorithms and data structures,
and how to use them with and from Python (or any language).  Eventually
you add to that graphical user interface development.

After that then you might be in a position to start thinking about how
to design and build a program that does what you were talking about.

There honestly are no shortcuts.  Python is a great language, and is
easy to learn, but it's not like you can start cranking out full-blown
applications magically.  In the hands of experienced programmers, yes
Python is incredibly fast and flexible for cranking out working apps.

You might try checking out a Python application development framework
that can produce apps that will run on Android and iOS (and Windows and
Linux) called Kivy.  I would think mobile should be your target platform
for such an app.

> 

> This seems to us like something software should help solve. We'd like
> to see teams tackling each of the component issues around saving and
> investing, along with ones tackling the entire package.

Are you wanting to contract with some programmers to create this
application for you?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: non-blocking getkey?

2015-11-19 Thread Ulli Horlacher
Terry Reedy  wrote:
> On 11/18/2015 11:50 AM, Ulli Horlacher wrote:
> > Ulli Horlacher  wrote:
> >
> >>  from Tkinter import Tk
> >>  from tkFileDialog import askopenfilename
> >>
> >>  Tk().withdraw()
> >>  file = askopenfilename()
> >
> > I found another glitch:
> >
> > After termination of askopenfilename() the window focus is not returned to
> > the calling window (xterm on Linux, cmd on Windows). I have to click it
> > again, to regain the focus and continue typing. Is there a workaround?
> 
> What happens with
> 
> root = Tk()
> root.withdraw()
> fiel = ...
> root.destroy()
> 
> Focus cannot stay with destroyed window.

The focus is moved to another, unrelated window, but not back to the
window in which the python scripts run. 
Same behaviour on Linux (XFCE) and windows 7.


-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-19 Thread Ian Kelly
On Thu, Nov 19, 2015 at 5:45 AM, Steven D'Aprano  wrote:
> But if you want the default value to be evaluated exactly once, and once
> only, there is no real alternative to early binding. You could use a global
> variable, of course, but that is no solution -- that's a problem waiting to
> happen.

It doesn't have to be a global. In a Python with late binding
defaults, this would work to get early binding:

def f(x=f.default_x):
...

f.default_x = something()

Of course, assignment to function attributes is a relatively modern
thing that is only permitted since Python 2.1, whereas function
defaults have been around since at least 1.4, so this wouldn't have
been an option when the semantics were being determined.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Writing a Financial Services App in Python

2015-11-19 Thread Cai Gengyang
It will be a web-based application. 

Something like this : https://www.slicedinvesting.com/, but with different, 
better, more features and also graphics , forums, a system to track your daily, 
monthly expenses and earnings, a graphical tutorial system to teach users 
financial literacy , learn and utilise ways to invest and trade their money 
properly and create computerised trend following systems to trade stocks in the 
stock market. 

The truth is, very few individual investors really know how to properly trade 
stocks , and hedge funds are open to mainly very wealthy clients. Computerised 
and automated trend following systems can legally create huge profits for 
investors if a disciplined automated systems are utilised. 

I for example, am a terrible trader because of having almost zero discipline 
and thus keep losing money. My plan is to create such an all-in-one platform to 
help individual users like myself who might not have millions of dollars to 
invest in professional hedge funds properly invest , trade , keep track of 
their money and also network with our individual investors. 



On Thursday, November 19, 2015 at 11:03:50 PM UTC+8, Jeremy Leonard wrote:
> On Thursday, November 19, 2015 at 7:00:05 AM UTC-5, Cai Gengyang wrote:
> > From YCombinator's new RFS, This is the problem I want to solve as it is a 
> > severe problem I face myself and something I need. I want to write this app 
> > in Python as I heard that Python is a great language that many programmers 
> > use ... How / where do I start ? The problem is detailed below :
> > 
> > FINANCIAL SERVICES
> > 
> > Saving money is hard and Americans are particularly bad at it. Because the 
> > personal savings rate has largely been falling since the early 80s, we 
> > don't have sufficient cushions to face economic shocks, weather unexpected 
> > unemployment, or even enjoy our retirements.
> > Its simply too hard to find good ways to save or to invest. Savings 
> > accounts only pay a fraction of what's needed to keep up with inflation. 
> > Picking individual stocks and bonds exposes investors to huge volatility 
> > and does nothing to guarantee a return.
> > 
> > While investors can dampen their volatility through various exchanges or 
> > closed ended funds, the reality is that few have the expertise needed to 
> > properly mix those funds, rebalance them, and optimize them for taxes to 
> > capture the best possible return (no matter how you define that) given each 
> > dollar of invested capital. Even if investors were able to pick optimal 
> > investment strategies, they'd find that that fees are a huge drag on 
> > performance.
> > 
> > This seems to us like something software should help solve. We'd like to 
> > see teams tackling each of the component issues around saving and 
> > investing, along with ones tackling the entire package.
> > 
> > 
> > Thanks alot !
> > 
> > Cai Gengyang
> 
> What platform do you want the app to target (web/desktop/etc...)?
> 
> Jeremy
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Writing a Financial Services App in Python

2015-11-19 Thread Jeremy Leonard
On Thursday, November 19, 2015 at 7:00:05 AM UTC-5, Cai Gengyang wrote:
> From YCombinator's new RFS, This is the problem I want to solve as it is a 
> severe problem I face myself and something I need. I want to write this app 
> in Python as I heard that Python is a great language that many programmers 
> use ... How / where do I start ? The problem is detailed below :
> 
> FINANCIAL SERVICES
> 
> Saving money is hard and Americans are particularly bad at it. Because the 
> personal savings rate has largely been falling since the early 80s, we don't 
> have sufficient cushions to face economic shocks, weather unexpected 
> unemployment, or even enjoy our retirements.
> Its simply too hard to find good ways to save or to invest. Savings accounts 
> only pay a fraction of what's needed to keep up with inflation. Picking 
> individual stocks and bonds exposes investors to huge volatility and does 
> nothing to guarantee a return.
> 
> While investors can dampen their volatility through various exchanges or 
> closed ended funds, the reality is that few have the expertise needed to 
> properly mix those funds, rebalance them, and optimize them for taxes to 
> capture the best possible return (no matter how you define that) given each 
> dollar of invested capital. Even if investors were able to pick optimal 
> investment strategies, they'd find that that fees are a huge drag on 
> performance.
> 
> This seems to us like something software should help solve. We'd like to see 
> teams tackling each of the component issues around saving and investing, 
> along with ones tackling the entire package.
> 
> 
> Thanks alot !
> 
> Cai Gengyang

What platform do you want the app to target (web/desktop/etc...)?

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


EuroPython 2016: Kick-off

2015-11-19 Thread M.-A. Lemburg
The EuroPython 2016 Team is ready for starting the organization of
next year’s event:


*** http://ep2016.europython.eu/ ***

 July 17 - 24 2016


If you would like to actively help with the organization, we’d love to
have you as volunteer in one of our workgroups. Please see the
EuroPython Workgroups page for how to sign up.

On-site Team WG


One of the workgroups, the on-site team workgroup, is especially
important, since they provide the services and management on-site in
Bilbao, as well as in the case of EuroPython 2016, also take on a
major role in the financial and legal infrastructure of the conference
organization.

This team is your contact in case you have questions related to
on-site setups.

 * Oier Echaniz Beneitez (Chair)
 * Borja Ayerdi Vilches
 * Darya Chyzhyk
 * Ion Marqués
 * José David Nuñez
 * Alexandre Savio
 * Luis Javier Salvatierra

Conference Administration WG


Manages and organizes the administration side of the conference, in
particular: contracts, venue contact, ticket support, satellite
conferences, legal support, insurance, licensing.

 * Marc-Andre Lemburg (Chair)
 * Borja Ayerdi Vilches
 * Vicky Twomey-Lee
 * Stéphane Wirtel

Finance WG
--

Manages and organizes the finances and budget of the conference, in
particular: budget, controlling, accounting, billing, invoicing,
taxes, payment system administration.

 * Borja Ayerdi Vilches (Chair)
 * Darya Chyzhyk
 * Marc-Andre Lemburg
 * Anthon van der Neut (EPS Treasurer)
 * Stéphane Wirtel

Sponsors WG
---

Manages and organizes the sponsor activities of the conference, in
particular: sponsor contacts, sponsor logistics, room/booth
assignment, recruiting session, jobs fair, exhibit hall, startup row.

 * Fabio Pilger (Chair)
 * Borja Ayerdi Vilches
 * Darya Chyzhyk
 * Raúl Cumplido
 * Marc-Andre Lemburg
 * Alexandre Savio
 * Vicky Twomey-Lee

Communications WG
-

Manages and organizes the public communication and community relations
of the conference, in particular: press, community relations,
diversity/outreach/CoC, CoC contact, announcements, social media,
attendee tools, volunteer coordination, mailing lists, Trello and
Loomio groups.

 * Marc-Andre Lemburg (Chair)
 * Darya Chyzhyk
 * Raúl Cumplido
 * Kerstin Kollmann
 * Leire Ozaeta
 * Vicky Twomey-Lee
 * Chris Ward
 * Stéphane Wirtel

Support WG
--

Manages and organizes the attendee/speaker support of the conference,
in particular: helpdesk, attendee support contact, visa help, travel
management.

 * Christian Barra
 * Aisha Bello
 * Darya Chyzhyk
 * Anthon van der Neut
 * Alexandre Savio
 * Stéphane Wirtel

Financial Aid WG


Manages and organizes the financial aid program of the conference, in
particular: setup, grant selection, aid organisation.

 * Darya Chyzhyk
 * Vicky Twomey-Lee
 * Stéphane Wirtel

Marketing/Design WG
---

Create and manage marketing and design aspects of the conference, in
particular: brochures, advertisements, banners, flyers, travel guide,
t-shirts, lanyards, badges, panels, logo.

 * Darya Chyzhyk
 * Marc-Andre Lemburg
 * Alexandre Savio
 * Stéphane Wirtel

Program WG
--

Manages and organizes the conference program of the conference, in
particular: talk selection/voting, scheduling, session chairs,
sprint/openspace/keynote/lightning talks/poster session organization.

 * Alexandre Savio (Chair)
 * Alexander Hendorf  (Co-chair)
 * Christian Barra
 * Raúl Cumplido
 * Moshe Goldstein
 * Vicky Twomey-Lee
 * Chris Ward

Web WG
--

Manages and organizes the web site, in particular: web site support,
helpdesk ticket system, administration, backups, payment system
integration, hosting.

 * Christian Barra (Chair)
 * Oier Beneitez
 * Raúl Cumplido
 * Cesar Desales
 * Patrick Guido
 * Marc-Andre Lemburg
 * Fabio Pliger
 * Alexandre Savio
 * Stéphane Wirtel

Media WG


Manage and organize the talk and session recordings of the conference,
in particular: video recording, live streaming, uploads to YouTube and
archive.org.

 * Anthon van der Neut (Chair)
 * Luis Javier Salvatierra

Code of Conduct WG
--

Manage and organize the code of conduct (CoC) workflows, create CoC
documents, provide CoC contacts and handle CoC requests.

 * Darya Chyzhyk
 * Marc-Andre Lemburg
 * Anthon van der Neut
 * Leire Ozaeta

On-Site Volunteers
--

In addition to several of the EuroPython Workgroup members, we will
need quite a few attendees helping us as session manager, room
manager, at the registration desk, bag stuffing and during set up and
tear down of the conference.

We will run a separate announcement for on-site volunteers closer to
the event.


Enjoy,
--
EuroPython Society
http://www.europython-society.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-19 Thread Chris Angelico
On Fri, Nov 20, 2015 at 12:19 AM, BartC  wrote:
> You presumably think differently because you have some inside knowledge of
> how Python works, and know that that [] undergoes a one-time assignment to a
> local, persistent 'default' variable where it's value can indeed by changed.
> (Thanks to another Python feature where an assignment is a very shallow copy
> of an object.) And it is that volatile variable that is the actual default.
>
> But not everyone is going to know that.

Correct: We think certain things because we understand how Python
behaves. You, too, can join the Inner Circle of Pythonistas; all you
have to do is read this (and/or watch the video):

http://nedbatchelder.com/text/names1.html

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


Re: pyinstaller and Python 3.5 on Windows?

2015-11-19 Thread Ulli Horlacher
Ulli Horlacher  wrote:

> C:\Users\admin>pip install pypiwin32
> Collecting pypiwin32
>   Downloading pypiwin32-219-cp35-none-win32.whl (7.9MB)
> 100% || 7.9MB 61kB/s
> Installing collected packages: pypiwin32
> Exception:
(...)
> PermissionError: [Errno 13] Permission denied: 'c:\\program files 
> (x86)\\python
> 3.5\\Lib\\site-packages\\PyWin32.chm'
> 
> 
> Why "Permission denied"? I am logged in as administrator! Stupid Windows...

I found, I have to deactivate Windows UAC with 
C:\Windows\System32\UserAccountControlSettings.exe

Then I was able to run

pip install pypiwin32
pip install pyinstaller

without errors.

BUT pyinstaller does not work:

S:\python>pyinstaller.exe --onefile tk.py
failed to create process.

S:\python>pyinstaller --version
failed to create process.

-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-19 Thread BartC

On 19/11/2015 12:19, Steven D'Aprano wrote:

On Thu, 19 Nov 2015 10:14 am, BartC wrote:



Consider this pair of functions:


def expensive():
 # Simulate some expensive calculation or procedure.
 time.sleep(100)
 return random.randint(1, 6)


def demo(arg=expensive()):
 return arg + 1


Now we call the second function four times, without an argument so that the
default value is used:

demo()
demo()
demo()
demo()

What results do you expect?


If someone /wants/ expensive() to be called each time, then why not? If 
they don't, then it seems easy enough to write:


demo_default=expensive()
def demo(arg=demo_default):
...

(As you mention later...)


- if the language defaults to early binding, it is *easy* for the
   programmer to get late binding semantics;

- if the language defaults to late binding, it is *very difficult*
   for the programmer to get early binding semantics.


I got the impression that Python was a nice, easy language for everyone 
to use. Not one where you need a Master's degree in CS to understand the 
nuances of! And to understand why something that is so blindingly 
obvious doesn't work.



But let's try going the other way. Suppose function defaults were evaluated
each and every time you called the function. How could you *avoid* the
expense and waste of re-evaluating the default over and over again?


I use default parameters a lot in other languages.

99% of the time the default value is a constant. And most often that 
constant is 0, "" or an empty list.


You want these very common examples to /just work/ instead of going to 
lengths trying to explain why they don't.



You can't, or at least, not cleanly and easily. The most obvious way is to
use a global variable:

ARG = expensive()

def demo(arg=ARG):
 ...

This is ... horrible. You are still evaluating the default each time,


I implement an interpreted language where these calls:

  demo()
  demo(ARG)

would have exactly the same cost.

I understand that Python is very different: at the call-site, the 
compiler has no idea of the number of arguments a function defines or 
what the default values might be, or even if it is a function that is 
being called.


But even under those circumstances, I would endeavour to make such a 
function call as fast as is practical.


(That could involve a runtime check on number of parameters, 
substituting the equivalent of None for missing ones, or whatever 
default expression has been declared.


But here, I am benefiting from my language not being Python which does 
seem to like making things difficult.)



but at
least it is only a global variable lookup,


Maybe you can wrap the entire module inside a function? Other than a bit 
at the end that calls that function. Does that solve the global lookup 
problem?



When you deal with mutable objects, you have to expect them to mutate. The
whole point of mutability is that their value can change.


That [] doesn't look like an object that could change. It looks like an 
empty list constructor. You would expect a constructor for an empty list 
to yield an empty list throughout a program! (As it does, in most other 
contexts.)


You presumably think differently because you have some inside knowledge 
of how Python works, and know that that [] undergoes a one-time 
assignment to a local, persistent 'default' variable where it's value 
can indeed by changed. (Thanks to another Python feature where an 
assignment is a very shallow copy of an object.) And it is that volatile 
variable that is the actual default.


But not everyone is going to know that.

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


Re: What is a function parameter =[] for?

2015-11-19 Thread Steven D'Aprano
On Thu, 19 Nov 2015 10:41 pm, BartC wrote:


> I expect the version with the default argument to be
> exactly the same as the last lot of calls, namely for:
> 
> fn()
> fn()
> fn()
> 
> to be equivalent to:
> 
> temp=[]
> fn(temp)
> temp=[]
> fn(temp)
> temp=[]
> fn(temp)

Why on earth would you expect that?

I don't mean that it isn't sometimes useful. Of course it is sometimes
useful, there's no doubt about that. But why would you expect the language
to default to the *slow*, *expensive*, *complicated* behaviour instead of
the *fast*, *cheap*, *simple* behaviour?

You already have one way to set the argument to a fresh list every time you
call the function: put the code you want executed inside the body of the
function. There's no need for a *second* way to get the same result.

But if you want the default value to be evaluated exactly once, and once
only, there is no real alternative to early binding. You could use a global
variable, of course, but that is no solution -- that's a problem waiting to
happen.

To get late binding, the interpreter needs to record the default expression
*and its scope* in some sort of executable code. The traditional name for
that is stolen from Algol, "thunk". And you need to decide whether it will
behave like a closure or not.

It needs to work sensibly with code like this:


i = j = k = -1
def demo():
array = []
for i in range(5):
def factory():
j = i
def f(x=i + i**2, y=3*j+1, z=k**2 - k):
return ((x, y, z), (i, j, k))
return f
array.append(factory())
return array

func = demo()[1]
i = j = k = 
print(func())


>> The distinction is exactly the same. If you can understand that the
>> first one constructs a single object and uses it three times, then you
>> should be able to understand that the function default is also
>> constructed once and used every time.
> 
> As I said, it's bizarre. It means that for certain types, Python doesn't
> have a default that works per call, but only a default that works once
> per program.

Nonsense. The semantics of default values is *completely* independent of the
type. Python ALWAYS uses early binding, regardless of the type. Whether the
default is an int, None, a list, a dict, a float, or some other instance,
the behaviour is the same: the default value is the specific instance which
the default expression evaluates to when the function is created.


-- 
Steven

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


Re: pyinstaller and Python 3.5 on Windows?

2015-11-19 Thread Ulli Horlacher
Kevin Walzer  wrote:

> I understand that Python 3.5 has shipped how the MS dll's from Visual 
> Studio are shipped, and perhaps the freezing tools (pyinstaller, py2exe) 
> haven't yet caught up. Consider filing a bug with the pyinstaller 
> developers.

http://pythonhosted.org/PyInstaller/#windows

  Installing in Windows

  For Windows, PyWin32 or the more recent pypiwin32, is a prerequisite.
  The latter is installed automatically when you install PyInstaller using
  pip or easy_install. If necessary, follow the pypiwin32 link to install
  it manually.

I have installed PyInstaller using "pip install pyinstaller".

Ok, then:

C:\Users\admin>pip install pywin32
Collecting pywin32
  Could not find a version that satisfies the requirement pywin32 (from 
versions: )
  Some externally hosted files were ignored as access to them may be unreliable
(use --allow-external pywin32 to allow).
No matching distribution found for pywin32


C:\Users\admin>pip install pypiwin32
Collecting pypiwin32
  Downloading pypiwin32-219-cp35-none-win32.whl (7.9MB)
100% || 7.9MB 61kB/s
Installing collected packages: pypiwin32
Exception:
Traceback (most recent call last):
  File "c:\program files (x86)\python 3.5\lib\site-packages\pip\basecommand.py",
 line 211, in main
status = self.run(options, args)
  File "c:\program files (x86)\python 3.5\lib\site-packages\pip\commands\install
.py", line 311, in run
root=options.root_path,
  File "c:\program files (x86)\python 3.5\lib\site-packages\pip\req\req_set.py",
 line 646, in install
**kwargs
  File "c:\program files (x86)\python 3.5\lib\site-packages\pip\req\req_install.
py", line 803, in install
self.move_wheel_files(self.source_dir, root=root)
  File "c:\program files (x86)\python 3.5\lib\site-packages\pip\req\req_install.
py", line 998, in move_wheel_files
isolated=self.isolated,
  File "c:\program files (x86)\python 3.5\lib\site-packages\pip\wheel.py", line
339, in move_wheel_files
clobber(source, lib_dir, True)
  File "c:\program files (x86)\python 3.5\lib\site-packages\pip\wheel.py", line
317, in clobber
shutil.copyfile(srcfile, destfile)
  File "c:\program files (x86)\python 3.5\lib\shutil.py", line 115, in copyfile
with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'c:\\program files (x86)\\python
3.5\\Lib\\site-packages\\PyWin32.chm'


Why "Permission denied"? I am logged in as administrator! Stupid Windows...


Then https://pypi.python.org/pypi/pypiwin32/219 :

pypiwin32-219-cp35-none-win32.whl  Python Wheelcp35 2015-01-09 7MB

"Python Wheel"?!

http://python-packaging-user-guide.readthedocs.org/en/latest/installing/#install-pip-setuptools-and-wheel

C:\Users\admin>pip install wheel
Collecting wheel
  Downloading wheel-0.26.0-py2.py3-none-any.whl (63kB)
100% || 65kB 1.3MB/s
Installing collected packages: wheel
  Failed to write executable - trying to use .deleteme logic
Exception:
Traceback (most recent call last):
  File "c:\program files (x86)\python 3.5\lib\site-packages\pip\_vendor\distlib\
scripts.py", line 209, in _write_script
self._fileop.write_binary_file(outname, script_bytes)
  File "c:\program files (x86)\python 3.5\lib\site-packages\pip\_vendor\distlib\
util.py", line 388, in write_binary_file
with open(path, 'wb') as f:
PermissionError: [Errno 13] Permission denied: 'c:\\program files (x86)\\python
3.5\\Scripts\\wheel.exe'


Looks like I have a broken Windows :-(

-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-19 Thread Steven D'Aprano
On Thu, 19 Nov 2015 10:14 am, BartC wrote:

> On 18/11/2015 22:11, Ian Kelly wrote:

>> The list0 parameter has a default value, which is [], an initially
>> empty list. The default value is evaluated when the function is
>> defined, not when it is called, so the same list object is used each
>> time and changes to the list are consequently retained between calls.
> 
> That is really bizarre behaviour.

It is standard early binding behaviour, applied to function defaults.

Early versus late binding crops up in many places when programming:

https://support.microsoft.com/en-us/kb/245115

http://javascript.info/tutorial/binding

https://msdn.microsoft.com/en-us/library/0tcf61s1.aspx

Unfortunately, like many evocative or useful terms in computing, it the term
isn't used consistently. There are at least two related, but distinct, uses
for "early/late binding", and Wikipedia only talks about the *other* one:

https://en.wikipedia.org/wiki/Late_binding

In Python terms, *all* (or nearly all?) name binding (assignment) is
equivalent to C++ late binding, a.k.a. "dynamic dispatch". But Python also
uses early/late binding to refer to when the default object is assigned.

Consider this pair of functions:


def expensive():
# Simulate some expensive calculation or procedure.
time.sleep(100)
return random.randint(1, 6)


def demo(arg=expensive()):
return arg + 1


Now we call the second function four times, without an argument so that the
default value is used:

demo()
demo()
demo()
demo()

What results do you expect?

There are two standard behaviours:

Early binding means that the default value is generated *once*, when the
function `demo` is created. That's expensive, but it only gets used once,
and the default value is now fixed, and can be retrieved almost instantly
in subsequent calls. That's what Python uses.

Late binding means that the default value is generated every time you call
the function. That's expensive, and confusing. Why is the function
parameter list being re-evaluated each time the function is called? Why is
the default value different each time I call the function? Now *that's*
bizarre.

Compared to the weirdness of late binding, Python's early binding makes much
more sense.

Another advantage of early binding is that it involves a consistent
execution model: only the function body is executed when you call the
function, not the function declaration and parameter list.

def demo(arg=expensive()):  # declaration, including the parameter list
# function body is indented


Now it is easy to tell which part gets executed when: just look at the
indentation.

Both early and late binding are useful, so which should a language default
to? (Assuming it doesn't offer both.) I think that there is absolutely no
doubt that function defaults should use early binding. The overwhelming
advantage of early binding is this:

- if the language defaults to early binding, it is *easy* for the 
  programmer to get late binding semantics;

- if the language defaults to late binding, it is *very difficult*
  for the programmer to get early binding semantics.


Given early binding, like Python has, it is easy to get late binding
semantics. All you have to do is use a sentinel value, and move the code
you want to execute every time the function is called into the body of the
function. The most common sentinel is None:

def demo(arg=None):
if arg is None:
arg = expensive()
...


Now it is obvious that expensive() will be called each time you call demo()
(with no argument provided), since the call to expensive is inside the
function body.

But let's try going the other way. Suppose function defaults were evaluated
each and every time you called the function. How could you *avoid* the
expense and waste of re-evaluating the default over and over again?

You can't, or at least, not cleanly and easily. The most obvious way is to
use a global variable:

ARG = expensive()

def demo(arg=ARG):
...


This is ... horrible. You are still evaluating the default each time, but at
least it is only a global variable lookup, not an expensive function call.
But the cost is great. Now you have to pollute the module with a global
variable for every function that has a default value. This breaks
encapsulation -- the default value for the function is no longer visible in
the function's declaration, you have to hunt for it through your module.
And what if somebody changes the global, or deletes it?



> So, looking at some source code, a default value for certain types is
> only certain to be that value for the very first call of that function?

When you deal with mutable objects, you have to expect them to mutate. The
whole point of mutability is that their value can change.

If you use a mutable default object, it is still mutable, and can change its
value. If you don't want that, then use an immutable object.


>  > The default value is evaluated when the function is
>  > defined, not when it is called

Re: PubMed / Entrez

2015-11-19 Thread Laura Creighton
In a message of Thu, 19 Nov 2015 09:17:35 +0100, c.bu...@posteo.jp writes:
>I am looking for a way to use the PubMed (medical research search
>engine) API (aka Entrez) with Python3.
>
>Does anyone know packages for that?

https://pypi.python.org/pypi/Bio_Eutils/1.63

Or just get BioPython and use the Entrez from that.

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


Writing a Financial Services App in Python

2015-11-19 Thread Cai Gengyang

>From YCombinator's new RFS, This is the problem I want to solve as it is a 
>severe problem I face myself and something I need. I want to write this app in 
>Python as I heard that Python is a great language that many programmers use 
>... How / where do I start ? The problem is detailed below :

FINANCIAL SERVICES

Saving money is hard and Americans are particularly bad at it. Because the 
personal savings rate has largely been falling since the early 80s, we don't 
have sufficient cushions to face economic shocks, weather unexpected 
unemployment, or even enjoy our retirements.
Its simply too hard to find good ways to save or to invest. Savings accounts 
only pay a fraction of what's needed to keep up with inflation. Picking 
individual stocks and bonds exposes investors to huge volatility and does 
nothing to guarantee a return.

While investors can dampen their volatility through various exchanges or closed 
ended funds, the reality is that few have the expertise needed to properly mix 
those funds, rebalance them, and optimize them for taxes to capture the best 
possible return (no matter how you define that) given each dollar of invested 
capital. Even if investors were able to pick optimal investment strategies, 
they'd find that that fees are a huge drag on performance.

This seems to us like something software should help solve. We'd like to see 
teams tackling each of the component issues around saving and investing, along 
with ones tackling the entire package.


Thanks alot !

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


Re: What is a function parameter =[] for?

2015-11-19 Thread Chris Angelico
On Thu, Nov 19, 2015 at 10:41 PM, BartC  wrote:
> As I said, it's bizarre. It means that for certain types, Python doesn't
> have a default that works per call, but only a default that works once per
> program.

No, it's not "for certain types". Regardless of the type, the
expression that defines the default is evaluated at *function
definition*, not at each *function call*. (That's not the same as
"once per program", although for 99% of situations, it'll be
indistinguishable.)

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


Re: Public key encryption example.

2015-11-19 Thread Laura Creighton
In a message of Wed, 18 Nov 2015 16:18:28 -0700, Vincent Davis writes:
>This might be a "Let me Google that for you question", I tried.
>I am looking for the "simplest" example of sending(encrypting) and
>receiving(decrypting) using public key encryption. I am think of something
>along the lines of having all the keys in local files and saving and
>reading the message from a local file.
>
>Possibly using cryptography library elliptic-curve
>https://cryptography.io/en/latest/hazmat/primitives/asymmetric/ec/#elliptic-curve-signature-algorithms
>
>Surly there is an example out there?
>
>Vincent Davis

pycrypto does this.

https://pypi.python.org/pypi/pycrypto
code and diagrams here
http://www.laurentluce.com/posts/python-and-cryptography-with-pycrypto/

There really isn't much to it.

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


Re: how do I learn python ?

2015-11-19 Thread Steve Hayes
On Wed, 18 Nov 2015 04:58:30 +, ÏÄ»ªÁÖ  wrote:

> 


-- 
Steve Hayes from Tshwane, South Africa
Web:  http://www.khanya.org.za/stevesig.htm
Blog: http://khanya.wordpress.com
E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-19 Thread BartC

On 19/11/2015 01:59, Chris Angelico wrote:

On Thu, Nov 19, 2015 at 12:41 PM, BartC  wrote:

On 18/11/2015 23:22, Chris Angelico wrote:

On the contrary, it is certain always to be that exact object.


But, not the same value that appears as the default?


Nope. Mutable objects are never guaranteed to retain the same values.
That's kinda the point.


But, presumably you would expect:

 a = []

to always assign an empty list to a? You don't expect this:

 a = []
 a.append(10)
 b = []

that b now has the same value of a, namely [10]. Fortunately this isn't 
the case.



Sorry, I didn't understand any of that.



If you want to think of function defaults as being values, then yes.
But they're not. They're objects.


That's not much help to someone who *does* want the default to supply 
the same missing value that they don't want to bother remembering and/or 
writing in the call.


Surely the language is trying to help people not hinder. How many times 
after all is this behaviour actually wanted? It's the equivalent of:


fndefault=[]

def fn(a=fndefault):
a.append(10)
return a

where it is known that a and fndefault share the same mutable data. 
(Although I bet some people are still surprised by that!)



I suspect those same people (unless they are experts in the murky corners of
the language) would expect:



and not be dependent on fn's entire call history.


Tell me, do you expect these to do the same thing?

x = []
fn(x)
fn(x)
fn(x)

# or

fn([])
fn([])
fn([])


No I don't. But I expect the version with the default argument to be 
exactly the same as the last lot of calls, namely for:


fn()
fn()
fn()

to be equivalent to:

temp=[]
fn(temp)
temp=[]
fn(temp)
temp=[]
fn(temp)


The distinction is exactly the same. If you can understand that the
first one constructs a single object and uses it three times, then you
should be able to understand that the function default is also
constructed once and used every time.


As I said, it's bizarre. It means that for certain types, Python doesn't 
have a default that works per call, but only a default that works once 
per program.


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


Re: pyinstaller and Python 3.5 on Windows?

2015-11-19 Thread Kevin Walzer

On 11/18/15 5:46 PM, Ulli Horlacher wrote:


ImportError: DLL load failed: The specified module could not be found.


Is there a solution available?



I understand that Python 3.5 has shipped how the MS dll's from Visual 
Studio are shipped, and perhaps the freezing tools (pyinstaller, py2exe) 
haven't yet caught up. Consider filing a bug with the pyinstaller 
developers.


--Kevin

--
Kevin Walzer
Code by Kevin/Mobile Code by Kevin
http://www.codebykevin.com
http://www.wtmobilesoftware.com
--
https://mail.python.org/mailman/listinfo/python-list


Re: Is there an meaning of '[[]]' in a list?

2015-11-19 Thread Peter Otten
fl wrote:

> Hi,
> In the previous exercises, I see list:
> cc=[[],[],[]]
> 
> Then, I can have this:
> 
> ccc=[[[]],[[]],[[]]]
> 
> I can also have
> 
> ccc[0]
> Out[158]: [[]]
> 
> ccc[0]='o'
> 
> ccc
> Out[163]: ['o', [[]], [[]]]
> 
> 
> I have question: Is there any difference between [[]] and []?
> [[]] can have deeper assignment and use than
> 
> ccc[0]='o'

I'm sure with a little effort and a few experiments on the commandline you 
can answer your question yourself. Please limit your posts to c.l.py to 
those questions that are a little harder.

Hint: when you experiment with nested lists use numbers, not strings as list 
entries that are not lists themselves. Strings can confuse you about the 
nesting level:

>>> items = ["foo"]
>>> items[0]
'foo'
>>> items[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]
'f'


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


Re: What is a function parameter =[] for?

2015-11-19 Thread Steven D'Aprano
On Thu, 19 Nov 2015 11:34 am, fl wrote:

> This is my new
> question: What does 'del' do? It does not look like a thorough list
> deletion from the effect.

Of course not. Did you Read The Fine Manual? Or at least use the interactive
help function? At the Python prompt, enter:

help("del")

and you will see an explanation which includes this:

Deletion of a name removes the binding of that name  from 
the local or global namespace, depending on whether the 
name occurs in a ``global`` statement in the same code 
block.  If the name is unbound, a ``NameError`` exception 
will be raised.


Let us try it with the interactive interpreter:

If the name "x" doesn't exist, and you try to delete it, you get an error:

py> del x
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'x' is not defined

If "x" does exist, and you delete it, the name no longer exists:

py> x = 42
py> print(x)
42
py> del x
py> print(x)
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'x' is not defined

So "del" deletes **names**. 

What happens after the name is deleted? Then the garbage collector may run,
and destroy the object that was bound to the name, reclaiming the memory
used. But **only** if the object is safe to destroy, otherwise that would
lead to segmentation faults and memory corruption.


Here we have ONE object with TWO names:

py> a = [1, 2, 3, 4]
py> b = a
py> b.append(999)
py> print(a)
[1, 2, 3, 4, 999]

If we delete one of those names, the other name keeps the list alive:


py> del a
py> print(b)
[1, 2, 3, 4, 999]





-- 
Steven

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


Re: Is there an meaning of '[[]]' in a list?

2015-11-19 Thread Nagy László Zsolt

> I have question: Is there any difference between [[]] and []?
Yes.

[] - a list with zero elements. That is an empty list.
[[]] - A list with one element. (That element is an empty list.)

> [[]] can have deeper assignment and use than 
You can have it as deep as you want, if you have enough memory.

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


Is there an meaning of '[[]]' in a list?

2015-11-19 Thread fl
Hi,
In the previous exercises, I see list:
cc=[[],[],[]]

Then, I can have this:

ccc=[[[]],[[]],[[]]]

I can also have

ccc[0]
Out[158]: [[]]

ccc[0]='o'

ccc
Out[163]: ['o', [[]], [[]]]


I have question: Is there any difference between [[]] and []?
[[]] can have deeper assignment and use than 

ccc[0]='o'


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


Re: how do I learn python ?

2015-11-19 Thread Michiel Overtoom

> On 18 Nov 2015, at 05:58, 夏华林  wrote:
> (nothing)

You might want to start at https://www.python.org/about/gettingstarted/

PS. Leaving the body of an email or usenet article empty is considered bad form.

Greetings,

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


PubMed / Entrez

2015-11-19 Thread c.buhtz
I am looking for a way to use the PubMed (medical research search
engine) API (aka Entrez) with Python3.

Does anyone know packages for that?
-- 
GnuPGP-Key ID 0751A8EC
-- 
https://mail.python.org/mailman/listinfo/python-list


how do I learn python ?

2015-11-19 Thread 夏华林
  
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: handling of non-ASCII filenames?

2015-11-19 Thread Christian Gollwitzer

Am 19.11.15 um 08:54 schrieb Ulli Horlacher:

Christian Gollwitzer  wrote:

Am 18.11.15 um 17:45 schrieb Ulli Horlacher:

This is my encoding function:

def url_encode(s):
u = ''
for c in list(s):
  if match(r'[_=:,;<>()+.\w\-]',c):
u += c
  else:
u += '%' + c.encode("hex").upper()
return u




The quoting is applied to a UTF8 string.


encode("hex") works only with binary strings?
How do I convert a UTF8 string to binary?


It's right in the other line I showed you:

Apfelkiste:Tests chris$ python
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> u"blablüa".encode('utf8')
'blabl\xc3\xbca'
>>>

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


Re: handling of non-ASCII filenames?

2015-11-19 Thread Ulli Horlacher
Christian Gollwitzer  wrote:
> Am 18.11.15 um 17:45 schrieb Ulli Horlacher:
> > This is my encoding function:
> >
> > def url_encode(s):
> >u = ''
> >for c in list(s):
> >  if match(r'[_=:,;<>()+.\w\-]',c):
> >u += c
> >  else:
> >u += '%' + c.encode("hex").upper()
> >return u
> >
> >
> 
> The quoting is applied to a UTF8 string.

encode("hex") works only with binary strings?
How do I convert a UTF8 string to binary?



> But I think you shouldn't do it yourself, use a library function:
> 
> import urllib
> urllib.quote(yourstring.encode('utf8'))

It does not encode exactly the same way I need it.
Besides this, I want to understand how Python handles strings and
character encoding. 


-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list