Re: importing: what does "from" do?

2016-01-21 Thread Ian Kelly
On Jan 21, 2016 7:31 AM, "Charles T. Smith" 
wrote:
>
> What does "from (module) import (func)" do?

Approximately equivalent to:

import module
func = module.func

Except that it doesn't bind "module" to anything.

> Please don't tell me that I shouldn't ask because real programmers
> know not to have circular dependencies ...
>
> I have no idea what was imported before.  I just want to import hexdump().
> Unfortunately, this does not work:
>
>   from utilities import hexdump
>
> ImportError: cannot import name hexdump

What is utilities? Is it a module on your sys.path?

> Now, I shouldn't have a problem because the programmers before me didn't
> understand either, and so just duplicated it everywhere, but I'd really
> like to do it right.
>
> I would have thought that "from" would allow me to import just one
> symbol.  Now, for all the people just chomping at the bit to tell
> me about circular dependencies

What makes you think this is caused by circular dependencies? It could be,
but you really haven't given us enough information about what utilities is
to diagnose that.

> would you explain to me why I get this:
>
>   (PDB)hexdump(msg)
> *** NameError: name 'hexdump' is not defined

Probably because the name 'hexdump' is not defined.

> P.S. can I get a list of all the loaded symbols and/or modules?

What do you mean by "loaded"? Bound to a name in the main module? In the
globals of the current scope? In any module? Try the "dir" or "vars"
built-in.

You can get a view of all the *cached* modules by looking in the
sys.modules dict.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: importing: what does "from" do?

2016-01-21 Thread Ian Kelly
On Thu, Jan 21, 2016 at 8:12 AM, Charles T. Smith
 wrote:
>>> would you explain to me why I get this:
>>>
>>>   (PDB)hexdump(msg)
>>> *** NameError: name 'hexdump' is not defined
>>
>> Probably because the name 'hexdump' is not defined.
>
>
> If indeed it's not defined, then I wouldn't think there'd be a
> problem importing the module that defines it.

What happens if you just do 'import utilities'. Can you then call
utilities.hexdump? Can you see anything in the utilities module?

>  'hexdump': ,
>  'int.hexdump': None,
>
>
> But I suspect the first, at any rate, was loaded because of this in
> my ~/.pdbrc:
>
>   from hexdump import hexdump
>
> which wouldn't interfere when running without the debugger (that module
> in my sys.path but nowhere near my project)
>
>
> I have this in my project:
>
>   int/__init__.py
>
> But:
>
>   $ ls int/hexdump*
>   ls: cannot access int/hexdump*: No such file or directory
>
> So I don't really understand "int.hexdump".

The value of None in sys.modules caches a relative import miss. All it
means is that at some point something in the 'int' package tried to do
a relative import of the hexdump module and failed (presumably because
it doesn't exist).

Side observation: 'int' is a bad name for a package, because it will
shadow the name of the 'int' built-in.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: parallel (concurrent) eventlet

2016-01-18 Thread Ian Kelly
On Mon, Jan 18, 2016 at 8:03 AM, David Gabriel  wrote:
> Dears,
>
> Let me add one more detail: When I add these two lines to check whether my
> modules are monkey_patched or not I get *False* as a result.
> I think it is strange to get this result since I patched my modules at the
> beginning using: eventlet.monkey_patch() as detailed here
> .
>
> print "*is_monkey_patched(ldap.syncrepl) : %s*" %
> eventlet.patcher.is_monkey_patched('ldap.syncrepl')
> print "*is_monkey_patched(ldap.ldapobject) : %s*" %
> eventlet.patcher.is_monkey_patched('ldap.ldapobject')

In your code you monkey patched the standard library modules, not the
ldap modules, so I think it's unsurprising that these return False.

As to why the ldap modules are blocking, python-ldap uses the OpenLDAP
client which is written in C and thus using its own blocking socket
code rather than the Python socket module. I don't believe it is
possible to "green" that. Therefore I think your only option for
concurrency with python-ldap is threading. It is possible to use
threads in conjunction with eventlet; see
http://eventlet.net/doc/threading.html
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: When is an int not an int? Who can explain this?

2016-01-18 Thread Ian Kelly
On Mon, Jan 18, 2016 at 9:51 AM, Chris Angelico  wrote:
> On Tue, Jan 19, 2016 at 3:28 AM, Charles T. Smith
>> Okay, I think I understand it now:
>>
>> (PDB)type (int)
>> 
>>
>> (PDB)type (float)
>> 
>
> And that's pretty strong evidence right there! So the next question
> is... what got imported under the name 'int'?
>
> int.__name__ will be a start. If that just returns the string 'int',
> then try int.__package__ which might give a hint. Also, int.__file__
> will tell you where it was loaded from, if it was indeed loaded from a
> file.
>
> Armed with that information, you should be able to track down what's
> going on. It's curious, though, that you have a callable subclass of
> module bound to the name int. Very curious indeed.

What makes you think that it's a callable subclass? I don't see any
place in the posted transcript where int has been called.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pyton install Landmine

2016-01-16 Thread Ian Kelly
On Jan 16, 2016 3:02 AM, "JeffP"  wrote:
>
> Hi
> I installed pyth3.5 on my Windows machine and had some complications
trying  to connect other components.
> I installed to the default directory chosen by the installer but that
included a folder with an embedded space in the name. BIG NO NO

Program Files is the standard Windows installation location for non-OS
software and is selected as the default location as a security practice. If
the other components to which you refer are designed for Windows but cannot
correctly handle the space in Program Files, that sounds like a problem
with those components, not with Python.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Keen eyes

2016-01-16 Thread Ian Kelly
On Jan 17, 2016 12:16 AM, "Steven D'Aprano"  wrote:
>
> On Sun, 17 Jan 2016 10:25 am, jonas.thornv...@gmail.com wrote:
>
> > double use of j in two different functions
>
> Are you using a global variable called "j" as a loop variable? That sounds
> like a terrible idea.
>
> You should use local variables. Then a function with a local variable j
> cannot possibly effect another function with a local variable also called
> j.
>
> Wait... is somebody going to tell me that Javascript defaults to global
> variables inside functions?

Technically it defaults to non local. The var statement allocates a
variable within the current scope. Otherwise it searches up the chain of
parent scopes for a matching variable, terminating at the global scope.

I believe Lua also works this way.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: wxpython strange behaviour

2016-01-15 Thread Ian Kelly
On Fri, Jan 15, 2016 at 10:05 AM, Shiva Upreti  wrote:
> https://gist.github.com/anonymous/4baa67aafd04555eb4e6
>
> I wrote the above code to display a toasterbox, and I didnt want it to 
> display any frames on the screen, just a toasterbox. The problem with this 
> code is that it runs fine when I run it the first time, but when I run it 
> next time it shows some error and the toasterbox doesnt disappear from the 
> screen itself(it should though).
> Error message I got:
> https://gist.github.com/anonymous/f0d4ec685d2432c80a1

The first gist is short enough that it easily could have been included
inline in your message. The second gist is a 404 (looks like it may be
short one hex digit).

I haven't used wxPython in a while and I've never used that ToasterBox
widget, but I'll see what I can answer.

If you don't want any frames then you should probably use parent=None,
not parent=wx.Frame(None), which creates a frame. Also, the purpose of
the panel is unclear since it's never used.

When you say that you run it the next time, do you mean that you're
running this script twice, as two separate processes, and getting
different results? That seems strange. Or do you mean that you're
invoking this code multiple times in the same Python process?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Stop writing Python 4 incompatible code

2016-01-14 Thread Ian Kelly
On Thu, Jan 14, 2016 at 8:52 AM, Rick Johnson
 wrote:
> So you're suggesting that GvR *WILLINGLY* left a global, and
> well established giant, to work for a tiny start-up because
> his bosses refused to switch from Python2 to (his new baby)
> Pyhton3?
>
> So, let me get this strait: he wasn't fired, *HE QUIT*???

It's even still plausible if you just cut everything after the
"because" from that first sentence. People leave large companies like
Google to go work at start-ups where they believe they'll be able to
have more impact all the time.

It's certainly much more likely than your speculation that he was
fired because of Python 3. Google isn't in the habit of firing
talented engineers for idiotically trivial reasons so they can be
scooped up by the competition.

> I wonder if he's considered the possibility that Google may
> swoop in an purchase Dropbox at some time in the near
> future, and he could find himself working for google once
> again.

Google already has a cloud storage service.

> And you know what would be the ultimate form of
> irony, if they forced him to migrate Dropbox *BACK* to
> Python2!

What a ridiculous waste of programmer time that would be.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Python-ideas] Password masking for getpass.getpass

2016-01-13 Thread Ian Kelly
On Wed, Jan 13, 2016 at 3:19 AM, Chris Angelico  wrote:
> You're quite probably right that obfuscating the display is security
> theatre; but it's the security theatre that people are expecting. If
> you're about to enter your credit card details into a web form, does
> it really matter whether or not the form itself was downloaded over an
> encrypted link? But people are used to "look for the padlock", which
> means that NOT having the padlock will bother people. If you ask for a
> password and it gets displayed, people will wonder if they're entering
> it in the right place.

I realize that I'm taking this thread off-topic, but yes it's
important that the form itself be downloaded over a secure connection.
If I can MitM the form response over an insecure connection, then I
can also MitM the form itself. And if I can do that, then I can
deliver exactly the form you were expecting, but with an added script
that will read your credit card number as you type it and then fire it
off to be stored on my server before you've even hit the Submit
button.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I'm missing something here...

2016-01-12 Thread Ian Kelly
On Mon, Jan 11, 2016 at 6:04 PM, Skip Montanaro
 wrote:
> Sorry, I should have been explicit. prob_dates (the actual argument of the
> call) is a set. As far as I know pylint does no type inference, so pylint
> can't tell if the LHS and RHS of the |= operator are appropriate, nor can
> it tell if it has an update() method.
>
> Before writing, I had more-or-less concluded I had hit a bug, but in my
> experience when I hit something I think is a bug, it's not. It's me.
> Terry's reply convinced me that I had hit something.
>
> Something else just occurred to me. I should have tried disassembling the
> two versions of the function. Here's the output near prob_dates.update()
> call:
>
>  14
>
>62 LOAD_FAST3 (prob_dates)
>  65 LOAD_ATTR6 (update)
>  68 LOAD_GLOBAL  7 (compare_prices)
>  71 LOAD_CONST   3 ('E:%s')
>  74 LOAD_FAST5 (sym)
>  77 BINARY_MODULO
>  78 LOAD_FAST0 (cx1)
>  81 LOAD_FAST1 (cx2)
>  84 LOAD_FAST2 (cx3)
>  87 CALL_FUNCTION4
>  90 CALL_FUNCTION1
>
> Here's how the |= version disassembles in that region:
>
>  20
>
>  62 LOAD_FAST3 (prob_dates)
>  65 LOAD_GLOBAL  6 (compare_prices)
>  68 LOAD_CONST   3 ('E:%s')
>  71 LOAD_FAST5 (sym)
>  74 BINARY_MODULO
>  75 LOAD_FAST0 (cx1)
>  78 LOAD_FAST1 (cx2)
>  81 LOAD_FAST2 (cx3)
>  84 CALL_FUNCTION4
>  87 INPLACE_OR
>  88 STORE_FAST   3 (prob_dates)
>
> I think what's throwing pylint is that last
> STORE_FAST. That tells pylint the argument is ignored.

I may be wrong, but I believe pylint just looks at the AST, not the opcodes.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: When I need classes?

2016-01-12 Thread Ian Kelly
On Mon, Jan 11, 2016 at 5:53 PM, Bernardo Sulzbach
 wrote:
> I have never gone "seriously OO" with Python though. I never wrote
> from scratch an application with more than 10 classes as far as I can
> remember. However, I would suppose that the interpreter can handle
> thousands of user-defined classes simultaneously.

In Python, a class is just an object, so the only limit on how many
classes the interpreter can handle simultaneously is available memory.

However, if you have deeply nested inheritance graphs then you could
start to see performance issues on method calls, since the entire
inheritance graph potentially has to be traversed in order to find the
method.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict

2016-01-12 Thread Ian Kelly
On Tue, Jan 12, 2016 at 10:12 AM, Terry Reedy  wrote:
> Using the values views at intended (as an iterable):
>
 dv = d.values()
 next(iter(dv))
> 1

Good coding practice also dictates that whenever next is called, the
potential StopIteration exception must be caught unless it is clearly
intended to be propagated up to some generator. So more fully, this
should be something like:

dv = iter(d.values())
try:
next(dv)
except StopIteration:
raise IndexError("d is empty")

At which point it may be desirable to extract that into a utility function.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What use is '__reduce__'?

2016-01-08 Thread Ian Kelly
As you found by searching, __reduce__ is used to determine how
instances of the class are pickled. If the example you're using
doesn't do any pickling, then it's not really relevant to the example.
It's probably included so that it won't be missed when the code is
copied.

On Fri, Jan 8, 2016 at 9:42 AM, Robert  wrote:
> Hi,
>
> When I try to run the following code:
>
>
>
> /
> from collections import Counter, OrderedDict
>
> class OrderedCounter(Counter, OrderedDict):
>  'Counter that remembers the order elements are first seen'
>  def __repr__(self):
>  return '%s(%r)' % (self.__class__.__name__,
> OrderedDict(self))
>  def __reduce__(self):
>  return self.__class__, (OrderedDict(self),)
>
> oc = OrderedCounter('abracadabra')
> -
>
> I don't know the use of '__reduce__', even I look it up on Python website.
> On that website, it explains 'pickle' module:
> https://docs.python.org/2/library/pickle.html
>
> But the above example without import that module. Is it from built-in?
> Anyhow, I don't find a built-in explanation about '__reduce__'.
>
> What use of the above two new self methods are in class OrderedCounter?
>
> Thanks,
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is the fastest way to do 400 HTTP requests using requests library?

2016-01-05 Thread Ian Kelly
On Tue, Jan 5, 2016 at 10:02 AM, Paul Rubin  wrote:
> Steven D'Aprano  writes:
>> Maybe they're stress-testing a web server, or they just want to download
>> things in a rush.
>
> They're stress-testing a web server through a tor proxy?  This sounds
> abusive to me.
>
> I also wonder whether 400 referred to the HTTP 400 error code rather
> than the number of requests to be sent.  As in:
>
> - Layer 7 (“400 bad request”) attacks toward our web and application
>   servers, causing Linode Manager outages
>
> from http://status.linode.com/incidents/mmdbljlglnfd
> regarding a big DDOS attack that's been running against Linode.com
> (a VPS host) over the past couple weeks.

I had the same initial thought about the status code but dismissed it,
since why would somebody intentionally send a request that will return
a 400 status? I was not thinking about abuse though, so the DDoS
scenario did not occur to me.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is the fastest way to do 400 HTTP requests using requests library?

2016-01-04 Thread Ian Kelly
On Mon, Jan 4, 2016 at 4:38 PM, Steven D'Aprano  wrote:
> On Tue, 5 Jan 2016 07:50 am, livems...@gmail.com wrote:
>
>> So what is the fastest way to make 400 HTTP requests using "requests"
>> library and also using tor proxy?
>
>
> Since this will be I/O bound, not CPU bound, probably use separate threads.
>
> Push the 400 requests into a queue, then create N threads, where N will need
> to be determined by experiment, but will probably be something like 4 or 8,
> and let each thread pop a request from the queue as needed.
>
> Are you experienced with threads? Do you need further information about
> using threads and queues?

Also see the concurrent.futures module in the standard library, which
makes this sort of setup very simple to implement.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way importing a string object?

2016-01-04 Thread Ian Kelly
On Mon, Jan 4, 2016 at 5:49 PM,   wrote:
> For example,
>
> name = "test"  # test.py is a module's file
> import name

Yes, use the importlib.import_module function.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Consistent error

2016-01-03 Thread Ian Kelly
On Sun, Jan 3, 2016 at 8:59 AM,   wrote:
> Thanks Chris!
> Don't worry about the indent, will fix it
> I've rewritten it to this-
>
>  def get_algorithm_result( numlist ):
>>  largest = numlist[0]
>>  i = 1
>>  while ( i < len(numlist) ):
>  i = i + 1
>>if ( largest < numlist[i]):
>>  largest = numlist[i]
>>  numlist[i] = numlist[-1]
>>  numlist = [1,2,3,4,5]
>return largest

This is even harder to read than before since some of the lines are
now quoted and some are not.

>> def prime_number(x):
>>  return len([n for n in range(1, x + 1) if x % n == 0]) <= 2
>
> But it still gives the test_maximum_number_one error.
> Please if you have any ideas what else I should change or add, let me know. 
> Thanks!

It's hard to give any specific advice about fixing the unittest
failure without knowing what the test is testing. These two lines
don't seem to have anything to do with the algorithm that you quoted
in the first post, however:

>  numlist[i] = numlist[-1]
>  numlist = [1,2,3,4,5]

It looks like you should kill everything in this function after the
assignment to largest and then start reimplementing the algorithm
again from the " If Li is last number from  the list" step.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: using __getitem()__ correctly

2015-12-30 Thread Ian Kelly
On Wed, Dec 30, 2015 at 9:58 AM, Charles T. Smith
<cts.private.ya...@gmail.com> wrote:
> On Wed, 30 Dec 2015 08:35:57 -0700, Ian Kelly wrote:
>
>> On Dec 30, 2015 7:46 AM, "Charles T. Smith"
>> <cts.private.ya...@gmail.com> wrote:
>>> As is so often the case, in composing my answer to your question, I
>>> discovered a number of problems in my class (e.g. I was calling
>>> __getitem__() myself!), but I'm puzzled now how to proceed.  I thought
>>> the way you avoid triggering __getattr__() from within that was to use
>>> self.__dict__[name] but that doesn't work:
>>>
>>>   (PDB)p self.attrs.keys()
>>>   ['mcc', 'abc']
>>>   (PDB)p self.attrs.__dict__['abc']
>>>   *** KeyError: KeyError('abc',)
>>
>> What leads you to believe that this is triggering a call to __getattr__?
>> The KeyError probably just means that the key 'abc' wasn't found in the
>> dict.
>
>
> I meant, it doesn't work because I'm not getting at the attribute  Although 
> keys()
> sees it, it's not in the __dict__ attribute of attrs.  If it's not there, 
> where is it?

I think you're probably getting confused because there are three
different dicts at play here:

* Since your attrdict class inherits from dict, self.attrs is a dict.
* self.attrs.__dict__ is a *different* dict, used to store the
instance attributes of self.attrs.
* self.attrs.__class__.__dict__  is another different dict, used to
store the class attributes of attrdict.

The keys method that you're calling above is a method of the
self.attrs dict, which is where your attrdict's __setattr__ is setting
it. That's why you find it there but not in self.attrs.__dict__.

>> print "attrdict:av:__getattr__: autovivifying ", name
>> #self.__dict__.__setitem__ (name, self.__class__())
>> #self.__setitem__ (name, self.__class__()) self.__setattr__
>> (name, self.__class__())
>>
>> No reason to explicitly call __setitem__ or __setattr__ here. I'd
>> probably just do self[name] = self.__class__()
>
>
> The reason I used this is to avoid trigging the __setitem__() method:
>
>   self.__setattr__(name, self.__class__())
>
> which is invoked if I use the "self[name]" syntax.  But that didn't work.

But the body of your __setattr__ method is just "self[name] =
self.__class__()", which is the exact same code as what I suggested
and will still invoke __setitem__.

That said, I don't get why you're trying to avoid calling __setitem__.
If you're trying to store the attribute as a dict item, as you seem to
be doing, why shouldn't that dict's __setitem__ be involved?

> Is it just impossible to get at attributes without going through either
> __getattr__() or __getitem__()?

No.

>> Based on the preceding, you probably want to return the value you just
>> set in the dict, correct? So just return self[name].
>
>
> The problem is that then triggers the __getitem__() method and I don't
> know how to get to the attributes without triggering __getattr__().
>
> It's the interplay of the two that's killing me.

The only interplay of the two is what you have written into your class.

> In the example, if I have:
>
>   self.mcc = self.attrs.mcc
>
>
> The crux:
>
> Then __getattr__() triggers for the mcc.  If I try to use self.attrs['mcc']
> to get it, then that triggers __getitem__().  Okay, if the key is not an int,
> I'll go and get it and return it... unfortunately that triggers __getattr__(),
> an infinite loop.

How precisely are you trying to store these: as an attribute, or as a
dict item? If it's supposed to be in the dict, then why is your
__getitem__ trying to look up an attribute to begin with?

> class attrdict(dict):
> def __init__ (self, name = None):
> if name:
> self.update (name)
> print "attrdict: instantiated: ", name
>
> # AutoVivification
> def __getattr__ (self, name):
> print "attrdict:av:__getattr__: entered for ", name
> if name not in self.keys():
> print "attrdict:av:__getattr__: autovivifying ", name
> self[name] = self.__class__()
> return self[name]
>
> def __getitem__ (self, key):
> print "attrdict:av:__getitem__: entered for ", key
> if type (key) is int:  # TODO: support slices
> return self.__getitem__(key)

Here the method as written is just going to end up calling itself. You
probably want super(attrdict, self).__getitem__(key)

> return attrdict.__getattr__(self, key)

And here if you really want to access the instance attributes without
using __getattr__, just use self.__dict__[key].

I don't understand what it is that you're trying to accomplish here by
looking the key up in the instance attributes, though. It looks very
circular. I think you should clearly define where you expect the items
to be stored and then only check that location.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: using __getitem()__ correctly

2015-12-30 Thread Ian Kelly
On Wed, Dec 30, 2015 at 3:54 PM, Charles T. Smith
<cts.private.ya...@gmail.com> wrote:
> On Wed, 30 Dec 2015 13:40:44 -0700, Ian Kelly wrote:
>
>> On Wed, Dec 30, 2015 at 9:58 AM, Charles T. Smith
>>> The problem is that then triggers the __getitem__() method and I don't
>>> know how to get to the attributes without triggering __getattr__().
>>>
>>> It's the interplay of the two that's killing me.
>>
>> The only interplay of the two is what you have written into your class.
>>
>>> In the example, if I have:
>>>
>>>   self.mcc = self.attrs.mcc
>>>
>>>
>>> The crux:
>>>
>>> Then __getattr__() triggers for the mcc.  If I try to use
>>> self.attrs['mcc'] to get it, then that triggers __getitem__().  Okay,
>>> if the key is not an int, I'll go and get it and return it...
>>> unfortunately that triggers __getattr__(), an infinite loop.
>>
>> How precisely are you trying to store these: as an attribute, or as a
>> dict item? If it's supposed to be in the dict, then why is your
>> __getitem__ trying to look up an attribute to begin with?
>
>
>
> I don't understand this distinction between an "attribute" and a "dict item".
> attrdict is a stupid legacy class that inherits from a dictionary.  I think
> the intent was to be faster than a normal class, but I doubt there's any value
> to that.
>
> In any case, I thought that class attributes were, in fact, items of __dict__?

That's correct, but as I said in my previous message, self.attrs and
self.attrs.__dict__ are two different dicts, and you're confusing one
for the other. Maybe this will be illuminating:

>>> class mydict(dict): pass
...
>>> md = mydict()
>>> md['foo'] = 42  # Set an item in md
>>> md['foo']  # 'foo' exists as an item
42
>>> md.foo  # but not as an attribute
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'mydict' object has no attribute 'foo'
>>> md.__dict__['foo']  # and it's not in md.__dict__
Traceback (most recent call last):
  File "", line 1, in 
KeyError: 'foo'
>>> md.bar = 43  # Set an attribute on md
>>> md.bar  # 'bar' exists as an attribute
43
>>> md.__dict__['bar']  # and it's in md.__dict__
43
>>> md['bar']  # but it's not in md itself
Traceback (most recent call last):
  File "", line 1, in 
KeyError: 'bar'

And to hopefully drive the point home:

>>> md.items()
[('foo', 42)]
>>> md.__dict__.items()
[('bar', 43)]



> The reason that my __getitem__() is trying to look up an attribute is, I
> think, because this syntax triggers __getitem__ with a key of "mcc":
>
>   return self[name]
>
> Is that assumption wrong?

That assumption is correct, but this still doesn't explain to me why
you want __getitem__ to be looking up attributes, i.e. looking in
self.__dict__ when the expectation is that it would just look in self.

Is the goal here that self.foo and self['foo'] are the same thing? If
so, then you shouldn't need to worry about __getitem__ and __setitem__
at all. Just override your __getattr__ and __setattr__ to store
attributes in self instead of self.__dict__.

> Just to establish the concept, this horrible thing is showing some promise:
>
>   attriter = self.iteritems()
>   for attr in attriter:
>   if attr[0] == name:
>   return attr[1]

This is equivalent to but slower than "return self.get(name)". What
method is this in and what's the rest of the code? It's hard to
analyze your code in any helpful way when you keep changing it.

> (because the subscripts there are on a tuple type)

I don't know what this has to do with anything.

> But I concede I must be doing something fundamentally wrong because this
> assert is triggering:
> def __getattr__ (self, name):
> print "attrdict:av:__getattr__: entered for ", name
> assert name not in self.keys(), "attrdict:__getattr__: who lied?"

When does this trigger? What's calling it? What name is passed in?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Newbie: How to convert a tuple of strings into a tuple of ints

2015-12-30 Thread Ian Kelly
On Wed, Dec 30, 2015 at 3:46 PM,   wrote:
> How do I get from here
>
> t = ('1024', '1280')
>
> to
>
> t = (1024, 1280)

Deja vu: https://mail.python.org/pipermail/python-list/2015-December/701017.html
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: using __getitem()__ correctly

2015-12-30 Thread Ian Kelly
On Dec 30, 2015 7:46 AM, "Charles T. Smith"  wrote:
> As is so often the case, in composing my answer to your question, I discovered
> a number of problems in my class (e.g. I was calling __getitem__() myself!), 
> but
> I'm puzzled now how to proceed.  I thought the way you avoid triggering 
> __getattr__()
> from within that was to use self.__dict__[name] but that doesn't work:
>
>   (PDB)p self.attrs.keys()
>   ['mcc', 'abc']
>   (PDB)p self.attrs.__dict__['abc']
>   *** KeyError: KeyError('abc',)

What leads you to believe that this is triggering a call to
__getattr__? The KeyError probably just means that the key 'abc'
wasn't found in the dict.

> class attrdict(dict):
> def __init__ (self, name = None):
> if name:
> self.update (name)
> print "attrdict: instantiated: ", name
>
> # AutoVivification
> def __getattr__ (self, name):
> print "attrdict:av:__getattr__: entered for ", name  #, " in ", 
> self
> #if not name in self.__dict__.keys():
> if not name in self.keys():

Use the "not in" operator, e.g. "if name not in self.keys()".

> print "attrdict:av:__getattr__: autovivifying ", name
> #self.__dict__.__setitem__ (name, self.__class__())
> #self.__setitem__ (name, self.__class__())
> self.__setattr__ (name, self.__class__())

No reason to explicitly call __setitem__ or __setattr__ here. I'd
probably just do self[name] = self.__class__()

> #return self.__getitem__(name)
> #return self.__dict__.__getitem__(name)
> return self.__getattribute__ (name)

You shouldn't call __getattribute__ from __getattr__, because
__getattr__ is called from __getattribute__, so this would cause an
infinite loop.

Based on the preceding, you probably want to return the value you just
set in the dict, correct? So just return self[name].
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Importing constantly changing variables

2015-12-26 Thread Ian Kelly
On Sat, Dec 26, 2015 at 8:14 AM,   wrote:
> As you can see, I want the program to print all values each 5 seconds.
> When I run the file "main.py" it does print values every 5 seconds, BUT when 
> I manually change
> the values (e.g. airTemperture = 30 instead of 24) and save the file, nothing 
> changes -
> the old values keep on printing.

Changing the source code of a module isn't going to affect that module
in a running program if it's already been imported. You can use the
importlib.reload function to force a module to be reloaded, but this
is generally anti-recommended. If not done correctly it can result in
multiple versions of the module being simultaneously in use, leading
to confusing error conditions.

It sounds like you're not trying to update the code anyway, just the
data used in the code. For that, you'd be better off putting the data
in a data file that your "sensors.py" would read from and re-read on
every iteration.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Meaning and purpose of the Subject field (was: Ignore error with non-zero exit status)

2015-12-22 Thread Ian Kelly
On Tue, Dec 22, 2015 at 8:17 AM, Grant Edwards  wrote:
> On 2015-12-21, Steven D'Aprano  wrote:
>
>> So as far as I am concerned, if changes of subject line breaks threading for
>> you, so sad, too bad. Go without threading or use a better mail client.
>
> Same here.  After getting what is effectively a 

Re: Ignore error with non-zero exit status

2015-12-21 Thread Ian Kelly
On Sun, Dec 20, 2015 at 3:46 PM, Thomas 'PointedEars' Lahn
 wrote:
> Chris Angelico wrote:
>
>> On Mon, Dec 21, 2015 at 8:22 AM, Thomas 'PointedEars' Lahn
>>  wrote:
>
> It is supposed to be an attribution *line*, _not_ an attribution novel.
> Also, the “(was: …)” part is to be removed from the Subject header field
> value to complete the change of subject in a thread.

Better yet, please don't change the Subject header for trivial reasons
in the first place. This isn't just a Usenet group; it's also a
mailing list, and many MUAs rely on the Subject header for proper
threading.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Meaning and purpose of the Subject field (was: Ignore error with non-zero exit status)

2015-12-21 Thread Ian Kelly
On Mon, Dec 21, 2015 at 1:58 PM, Ben Finney <ben+pyt...@benfinney.id.au> wrote:
> Ian Kelly <ian.g.ke...@gmail.com> writes:
>> This isn't just a Usenet group; it's also a mailing list, and many
>> MUAs rely on the Subject header for proper threading.
>
> If such MUAs do that, they're misinterpreting the Subject field. Other
> fields are available with the explicit meaning of relating messages to
> each other regardless of what they discuss.
>
> If the correct fields are being mangled, then the correct place to apply
> pressure is on those who can fix that error. Let's not overload the
> Subject field to make up the lack.

It might just be Gmail.

http://webapps.stackexchange.com/questions/965/how-does-gmail-decide-to-thread-email-messages

I can't specifically recall if I've used any MUA other than Gmail that
even attempts threading email messages.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Ignore error with non-zero exit status

2015-12-21 Thread Ian Kelly
On Dec 21, 2015 4:55 PM, "Terry Reedy"  wrote:
>
> Nothing has changed since except for
> https://www.python.org/dev/peps/pep-0498/
> already added to 3.6.

https://xkcd.com/927/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Meaning and purpose of the Subject field (was: Ignore error with non-zero exit status)

2015-12-21 Thread Ian Kelly
On Mon, Dec 21, 2015 at 4:24 PM, Jon Ribbens
 wrote:
> On 2015-12-21, Steven D'Aprano  wrote:
>> The whole purpose of the change of subject is to indicate in a human-visible
>> way that the subject of the thread has changed, i.e. that it is a new
>> thread derived from the old one. If that breaks threading, oh well, it
>> breaks threading.
>
> That sounds a bit confused - if the *intention* of changing the
> subject line is to create a new thread, then breaking the thread
> is not "breaking threading" ;-)
>
>>> And, yes, fixing the mail clients of "everybody else in the world"
>>> might be a lovely idea but it is a little impractical to implement.
>>
>> Less impractical than insisting that "everybody else in the world" must
>> change their posting habits to suit those using broken mail clients.
>
> Fortunately I haven't suggested that.

Yes, I only requested that people not change the subject headers for
trivial reasons, by which I meant things like fixing typos (as in the
subject header change that brought about this thread). I also only
intended my request in the context of this forum, which is shared
between Usenet and mailing list users. Changing the subject header to
indicate a change in subject is, of course, fine.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Catogorising strings into random versus non-random

2015-12-21 Thread Ian Kelly
On Mon, Dec 21, 2015 at 9:40 AM, duncan smith  wrote:
> Finite state machine / transition matrix. Learn from some English text
> source. Then process your strings by lower casing, replacing underscores
> with spaces, removing trailing numeric characters etc. Base your score
> on something like the mean transition probability. I'd expect to see two
> pretty well separated groups of scores.

Sounds like a case for a Hidden Markov Model.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Should stdlib files contain 'narrow non breaking space' U+202F?

2015-12-17 Thread Ian Kelly
On Thu, Dec 17, 2015 at 4:05 PM, Mark Lawrence  wrote:
> The culprit character is hidden between "Issue #" and "20540" at line 400 of
> C:\Python35\Lib\multiprocessing\connection.py.
> https://bugs.python.org/issue20540 and
> https://hg.python.org/cpython/rev/125c24f47f3c refers.
>
> I'm asking as I've just spent 30 minutes tracking down why my debug code
> would bomb when running on 3.5, but not 2.7 or 3.2 through 3.4.

Probably not, but that's inside a comment, so whether the character is
U+202F or U+0020 shouldn't make any difference in how the code runs.
That seems like a Unicode bug if it does.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: error reading api with urllib

2015-12-16 Thread Ian Kelly
On Wed, Dec 16, 2015 at 3:12 PM, John Gordon  wrote:
> In <9aa21642-765b-4666-8c66-a6dab9928...@googlegroups.com> 
> simian...@gmail.com writes:
>
>> Bad Request
>> b''
>
>
> That probably means you aren't using one of the recognized methods
> (i.e. GET, POST, etc.)
>
> It doesn't look like you are specifying one of these methods on your
> Request object.  Try doing that.
>
> (It works in your browser because it defaults to GET automatically.)

urllib.request.Request also defaults to GET unless the request
includes data, in which case it defaults to POST. I would be more
inclined to suspect a problem with the stored procedure being called.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: error reading api with urllib

2015-12-16 Thread Ian Kelly
On Tue, Dec 15, 2015 at 7:46 PM, Simian  wrote:
> I added
>
> except urllib.error.HTTPError as e:
>  print('HTTP Errpr')
>  print('Error code: ', e.code)
>
> to my try and I recieve...
>
> 400: ('Bad Request',
>  'Bad request syntax or unsupported method'),
>
> but processing the string with a browser works fine.

Have you tried requesting the same URL with curl?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: subclassing collections.Counter

2015-12-15 Thread Ian Kelly
On Tue, Dec 15, 2015 at 9:20 AM, Pavlos Parissis
<pavlos.paris...@gmail.com> wrote:
> On 15/12/2015 05:11 μμ, Ian Kelly wrote:
>> On Tue, Dec 15, 2015 at 8:49 AM, Pavlos Parissis
>> <pavlos.paris...@gmail.com> wrote:
>>> Hi,
>>>
>>> I need to store values for metrics and return the average for some
>>> and the sum for the rest. Thus, I thought I could extend
>>> collections.Counter class by returning averages for some keys.
>>
>> Leave Counter out of it, as this is not what it's designed for. Write
>> a custom Metrics class, with each attribute being a pseudo-collection
>> that maintains a sum or average.
>>
>
> But then I will have to override a lot of magic methods, right?
> What is the real problem of extending Counter in the way I did?

Only the ones that you have use for. So far, you haven't indicated
that you need any. All you said about your use case was "I need to
store values for metrics."

If you want your metrics container to act like a dict, then my
suggestion would be to just use a dict, with pseudo-collections for
the values as above.

> Calling items() over the object doesn't call __getitem__ and I can't
> find in the doc which method I need to change, any ideas?

You can find the source at
https://hg.python.org/cpython/file/3.5/Lib/collections/__init__.py.
Counter subclasses dict but doesn't override items, so if you want to
change the behavior of items then you'll probably have to override
items.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: subclassing collections.Counter

2015-12-15 Thread Ian Kelly
On Tue, Dec 15, 2015 at 8:49 AM, Pavlos Parissis
 wrote:
> Hi,
>
> I need to store values for metrics and return the average for some
> and the sum for the rest. Thus, I thought I could extend
> collections.Counter class by returning averages for some keys.

Leave Counter out of it, as this is not what it's designed for. Write
a custom Metrics class, with each attribute being a pseudo-collection
that maintains a sum or average.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: subclassing collections.Counter

2015-12-15 Thread Ian Kelly
On Tue, Dec 15, 2015 at 10:43 AM, Pavlos Parissis
 wrote:
>> If you want your metrics container to act like a dict, then my
>> suggestion would be to just use a dict, with pseudo-collections for
>> the values as above.
>>
>
> If I understood you correctly, you are saying store all metrics in a
> dict and have a counter key as well to store the times metrics are
> pushed in, and then have a function to do the math. Am I right?

That would work, although I was actually thinking of something like this:

class SummedMetric:
def __init__(self):
self.total = 0
self.count = 0

@property
def average(self):
return self.total / self.count

def add(self, value):
self.total += value
self.count += 1

metrics = {}
for metric_name in all_metrics:
metrics[metric_name] = SummedMetric()

For averaged metrics, look at metrics['f'].average, otherwise look at
metrics['f'].total.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Try: rather than if :

2015-12-14 Thread Ian Kelly
On Mon, Dec 14, 2015 at 4:48 PM, Vincent Davis  wrote:
> On Mon, Dec 14, 2015 at 4:14 PM, Cameron Simpson  wrote:
>
>> First, notice that the code inside the try/except _only_ fetches the
>> attribute.  Your version calls the "write" attribute, and also accesses
>> handle.name. Either of those might also emit AttributeError, and should
>> probably not be silently caught.
>>
>
> I think the intent of the original code was to check if handle had the
> attribute "name", I don't think the attribute "write" was the issue.
>
> So then possibly this based on your suggestion:
> try:
> write = handel.write
> except AttributeError:
> raise

Except that catching an exception just to immediately re-raise it is
silly. This would be better:

try:
name = handle.name
except AttributeError:
pass
else:
handle.write("# Report_file: %s\n" % name)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Try: rather than if :

2015-12-14 Thread Ian Kelly
On Mon, Dec 14, 2015 at 3:38 PM, Vincent Davis  wrote:
> In the code below try is used to check if handle has the attribute name. It
> seems an if statement could be used. Is there reason one way would be
> better than another?

http://www.oranlooney.com/lbyl-vs-eafp/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Weird list conversion

2015-12-13 Thread Ian Kelly
On Sun, Dec 13, 2015 at 1:05 PM, KP  wrote:
> On Sunday, 13 December 2015 11:57:57 UTC-8, Laura Creighton  wrote:
>> In a message of Sun, 13 Dec 2015 11:45:19 -0800, KP writes:
>> >Hi all,
>> >
>> >  f = open("stairs.bin", "rb")
>> >  data = list(f.read(16))
>> >  print data
>> >
>> >returns
>> >
>> >['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', '\x00', 
>> >'\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00']
>> >
>> >The first byte of the file is 0x3D according to my hex editor, so why does 
>> >Python return '=' and not '\x3D'?
>> >
>> >As always, thanks for any help!
>>
>> 0x3d is the ascii code for '='
>
> I am aware of that - so is the rule that non-printables are returned in hex 
> notation whereas printables come in their ASCII representation?

What you're seeing there is the repr() of the string. The rule is that
it should be a printable representation that can be passed to eval to
reconstruct the string. The printable requirement means that NUL
should always come out escaped as '\x00' or perhaps '\0', but for
printable bytes escaping isn't necessary. I don't know if there's a
requirement that the repr of '\x3D' be '=', but it's probably the most
generally useful and I doubt that any implementation would depart from
that.

If you specifically want hex representations, then you could use hex(ord(foo)).

py> hex(ord('='))
'0x3d'
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Weird list conversion

2015-12-13 Thread Ian Kelly
On Sun, Dec 13, 2015 at 12:45 PM,   wrote:
> Hi all,
>
>   f = open("stairs.bin", "rb")
>   data = list(f.read(16))
>   print data
>
> returns
>
> ['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', 
> '\x00', '\x00', '\x00', '\x00', '\x00', '\x00']
>
> The first byte of the file is 0x3D according to my hex editor, so why does 
> Python return '=' and not '\x3D'?

They're equivalent representations of the same thing.

py> '\x3D'
'='
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Calling a list of functions

2015-12-13 Thread Ian Kelly
On Sun, Dec 13, 2015 at 10:26 AM, Ganesh Pal  wrote:
> Hi Team,
>
> Iam on linux and python 2.7  . I have a bunch of functions  which I
> have run sequentially .
> I have put them in a list and Iam calling the functions in the list as
> shown below ,  this works fine for me , please share your
> opinion/views on the same
>
>
> Sample code :
>
> def print1():
> print "one"
>
> def print2():
> print "two"
>
> def print3():
> print "three"
>
> print_test = [print1(),print2(),print3()] //calling the function

If I understand correctly, you want to build the list of functions and
then call them later. If so, this is not quite correct. This is
calling the functions at the time that you build the list and placing
the return values in the list, not the functions.

To build a list of the functions themselves, do:

print_test = [print1, print2, print3]

> for test in range(len(print_test)):

Iterating over range(len(something)) is usually not correct. Just
iterate over print_test instead. If you really need the indexes, then
iterate over enumerate(print_test).

>   try:
>   print_test[test]
>   except AssertionError as exc:

It looks like some code got cut off here since your exception handler
has no body. Regardless, the exception handler will never be invoked
because print_test[test] is just looking up the results of the
functions that were called when building the list.

To actually call the functions here instead of above, do:

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


Re: Python variable assigning problems...

2015-12-11 Thread Ian Kelly
On Fri, Dec 11, 2015 at 9:10 AM, ICT Ezy  wrote:
> Dear All,
> Very Sorry for the my mistake here. I code here with mu question ...
>
> My Question:
>
> A,B=C,D=10,11
> print(A,B,C,D)
> #(10,11,10,11) --> This is OK!
>
> a=1; b=2
> a,b=b,a
> print(a,b)
> # (1,2) --> This is OK!

This actually results in (2, 1), which is expected; you assign 1 to a
and 2 to b and then swap the values.

> x,y=y,x=2,3
> print(x,y)
> # (3,2) --> Question: How to explain it?
> # Not understand this process. Pl explain ...

The assignments happen from left to right. First, (2,3) is assigned to
(x,y), which has the effect of assigning 2 to x and then 3 to y. Next,
(2,3) is assigned to (y,x), whas the effect of assigning 2 to y and
then 3 to x, overwriting the previous assignments. Then when you do
the print, x has the value 3, and y has the value 2.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python variable assigning problems...

2015-12-11 Thread Ian Kelly
On Fri, Dec 11, 2015 at 9:24 AM, Robin Koch  wrote:
> Assigning goes from right to left:
>
> x,y=y,x=2,3
>
> <=>
>
> y, x = 2, 3
> x, y = y, x
>
> Otherwise the assignment x, y = y, x would not make any sense, since x and y
> haven't any values yet.
>
> And the execution from right to left is also a good choice, because one
> would like to do something like:
>
> x = y = z = 0
>
> Again, assigning from left to right woud lead to errors.

No, it actually happens left to right. "x = y = z = 0" means "assign 0
to x, then assign 0 to y, then assign 0 to z." It doesn't mean "assign
0 to z, then assign z to y, etc." This works:

>>> d = d['foo'] = {}
>>> d
{'foo': {...}}

This doesn't:

>>> del d
>>> d['foo'] = d = {}
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'd' is not defined
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python 351x64

2015-12-11 Thread Ian Kelly
On Fri, Dec 11, 2015 at 9:30 AM, Jay Hamm  wrote:
> Hi
>
> I was trying to use your windows version of python 3.5.1 x64.
>
> It has a conflict with a notepad++ plugin NppFTP giving 
> api-ms-win-crt-runtime-I1-1-0.dll error on start up.
>
> This seems pretty well documented on the web. The work around is to delete 
> the plugin and reinstall since it borks the install.
>
> Since about every other admin I've ever known uses notepad++, you might want 
> to fix this.

Laura Creighton has filed an issue based on your post to the Python
issue tracker at http://bugs.python.org/issue25842. Would you please
add some details on this issue? Googling for "python nppftp" failed to
turn up anything useful for me.

> Also your installer fails to set the permissions correctly:

How do you expect them to be set?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Hello

2015-12-11 Thread Ian Kelly
On Fri, Dec 11, 2015 at 11:43 AM, Seung Kim  wrote:
> See message below.
>
> On Fri, Dec 11, 2015 at 1:13 PM, Seung Kim  wrote:
>
>> I would like to have Python 3.5.1 MSI installer files for both 32-bit and
>> 64-bit so that I can deploy the software on managed computers on campus.
>>
>> When I ran the silent install command line on python-3.5.1.exe, the
>> registry key of QuietUninstallString showed me that the installer file was
>> located under the following C:\Users\css.kim\AppData\Local\Package
>> Cache\{b8440650-9dbe-4b7d-8167-6e0e3dcdf5d0}\python-3.5.1-amd64.exe"
>> /uninstall /quiet.
>>
>> If I deploy the latest version of Python 3.5.1, the source location will
>> be differently installed among managed computers. That is why I won't use
>> the exe installer file. I wanted to have MSI installer files.
>>
>> Please, advise.

You probably want to install for all users using the InstallAllUsers=1
option. See https://docs.python.org/3/using/windows.html#installing-without-ui
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Accessing container's methods

2015-12-08 Thread Ian Kelly
On Tue, Dec 8, 2015 at 3:37 PM, Erik  wrote:
> On 08/12/15 19:02, Thomas 'PointedEars' Lahn wrote:
>>
>> Erik wrote:
>> 
>> Please fix, Erik #75656.
>
>
> Fixed(*)

[SNIP]

> (*) In the sense that it's not going to change ;)

Then I think you mean "Working as Intended", not "Fixed".  B-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Accessing container's methods

2015-12-07 Thread Ian Kelly
On Mon, Dec 7, 2015 at 11:10 AM, Tony van der Hoff  wrote:
> Hi,
>
> I have a class A, containing embedded embedded classes, which need to access
> methods from A.
> .
> A highly contrived example, where I'm setting up an outer class in a Has-a
> relationship, containing a number of Actors. The inner class needs to access
> a method of the outer class; here the method get_name.
>
> I don't really want to make Actor a sub-class (is-a; it isn't) of Monty;
> that would raise all sorts of other problems.
>
> Can anyone please advise me on how to achieve this magic?

I'm guessing that you're coming from Java. Java has two different
types of nested classes: non-static, where an instance of the inner
class is implicitly associated with an instance of the outer class;
and static, where an instance of the inner class is unrelated to any
instance of the outer class.

It looks like you're trying to do the former, but Python only has the
static type of nested classes. So how would you go about creating a
nested class of the non-static type? Make the association explicit.
When Monty creates an Actor, pass it self as one of the arguments.
Actor can then save that instance of Monty in an attribute and call
the method thusly.

As others have noted, this does create a reference cycle. The Python
garbage collector is fine with cleaning up reference cycles as long as
there are no objects __del__ methods anywhere in the cycle, so it's up
to you whether you consider that to be a problem or not.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Understanding Python from a PHP coder's perspective

2015-12-07 Thread Ian Kelly
On Mon, Dec 7, 2015 at 2:07 PM,   wrote:
> Hello all!  Just started getting into Python, and am very excited about the 
> prospect.
>
> I am struggling on some general concepts.  My past experience with 
> server-side code is mostly limited to PHP and websites.  I have some file 
> called "whatever.php", the browser accesses it, and PHP parses it and returns 
> HTML, JSON, etc.  Every now and then, I need to run some background PHP 
> script, or have some PHP script initiated by a CRON job, or have some PHP 
> script initiated by the command line running in an endless loop, and while it 
> works, feel other languages might be more appropriate.
>
> So, my interest in Python...
>
> I've read up on Python, and while some aspects seem similar to PHP, some 
> don't.  I have learned how to create Python script, have run it from the 
> command line, and have even accessed it with Apache by placing 
> http://example.com/myscript.py in the browser.  I am used to seeing .php 
> extensions, but never .py extentions, and even visited multiple sites which I 
> knew were written in Python, but never saw the browser expose the .py 
> extensions.  I am obviously missing something.
>
> Why don't I see the .py extension in my browser?

PHP tends to be served like CGI, which is that the URL mirrors the
path to a script that lives under a particular directory, which the
webserver locates and executes. This has some downsides:

* It exposes details about the structure of your server to the public,
which is considered a security weakness.
* An improperly configured webserver might accidentally serve scripts
or other files that are not intended to be served over the web, which
is a much bigger security risk.
* It's inflexible; if you move your script, then the URL must
necessarily change as well.

With Python, it's more usual to have a greater abstraction between
URLs and code. A set of URLs are mapped to a single Python gateway,
and the gateway dispatches the request to the appropriate request
handler. With this scheme there is no reason to have .py extensions in
the URLs because the URL structure is unrelated to how the actual
scripts are organized in the file system. This also makes it easier to
create meaningful URLs: see
https://en.wikipedia.org/wiki/Semantic_URL.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Understanding Python from a PHP coder's perspective

2015-12-07 Thread Ian Kelly
On Mon, Dec 7, 2015 at 2:40 PM, Chris Angelico  wrote:
> So that's a quick potted summary of why the URLs don't reflect the
> language used. Python is event-driven, but instead of defining events
> at the file level, the way PHP does, they're defined at the function
> level. Of course, if you *want* to put ".py" on the end of all your
> URLs, Python won't stop you... :)

Or, if it's a poorly implemented site, ".rb". ;-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Understanding Python from a PHP coder's perspective

2015-12-07 Thread Ian Kelly
On Mon, Dec 7, 2015 at 3:27 PM,   wrote:
> Thank you all!
>
> Okay, the concept of a WSGI along with a framework provides insight on my 
> main questions.
>
> In regards to Chris's statement: "It openly and honestly does NOT reset its 
> state between page requests"
>
> With PHP, I have sessions to preserve state.  I have a feeling that this is 
> significantly different.  Yes?  How?  Does this somehow relate to how 
> websockets are implemented?

Session state is different from process state. Whether you start a new
process for each request or reuse an existing process has no bearing
on whether you're storing and reading data related to the user's
session (except that in the reuse case it's possible to cache the data
in-process, whereas an in-memory cache for a restarted process must be
in a separate process; but it's good practice to have your in-memory
cache in a separate process anyway).

I'm not sure where websockets come into this, as that's a completely
separate technology that is not used by most web apps.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Issue

2015-12-07 Thread Ian Kelly
On Sun, Dec 6, 2015 at 5:16 PM, Steven D'Aprano  wrote:
> Oh, I can make one guess... if you're using Windows XP, I'm afraid that
> Python 3.5 is not supported. You'll have to either downgrade to Python 3.4,
> or upgrade to Windows 7 or higher, or another operating system.

For the sake of accuracy, the requirement is actually Windows Vista or higher.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: increment/decrement operators

2015-12-07 Thread Ian Kelly
On Dec 5, 2015 10:21 AM, "BartC"  wrote:

>

>

> The latter is not the same. Some of the differences are:

>

> * ++ and -- are often inside inside expressions and return values (unlike
x+=1 in Python)

>

> * x++ and x-- return the /current/ value of x, unlike x+=1 even if it
were to return a value; it would be the new value

Since x+=1 is not an expression, this is moot.

> * x+=1 requires you to hard-code the value 1, but ++ is not necessarily
stepping by 1. You can imagine ++ stepping something to its next value.

Note that x+=1 does not necessarily have to mean stepping by 1 either. You
could even do something like x+=5 to mean skip the next four values and
step x to the value after that.

> However, if ++ and -- are only used as statements, then why not simply
map them to x+=1? In Python, that would need to be x++ and x-- as ++x or
--x have existing meanings.

I think a better question is if they're only going to be statements, then
why bother adding them? x++ doesn't give you anything you can't get from
x+=1, so why commit to supporting the extra syntax?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Python-ideas] Missing Core Feature: + - * / | & do not call __getattr__

2015-12-04 Thread Ian Kelly
On Fri, Dec 4, 2015 at 7:20 AM, Stephan Sahm  wrote:
> Dear all,
>
> I just stumbled upon a very weird behaviour of python 2 and python 3. At
> least I was not able to find a solution.
>
> The point is to dynamically define __add__, __or__ and so on via __getattr__
> (for example by deriving them from __iadd__ or similar in a generic way).
> However this very intuitive idea is currently NOT POSSIBLE because * - * / &
> | and so on just bypass this standard procedure.
>
> I found two stackoverflow contributions stating this:
> http://stackoverflow.com/questions/11629287/python-how-to-forward-an-instances-method-call-to-its-attribute
> http://stackoverflow.com/questions/33393474/lazy-evaluation-forward-operations-to-deferred-value
>
> Neither the mentioned posts, nor I myself can see any reason why this is the
> way it is, nor how the operators are actually implemented to maybe bypass
> this unintuitive behaviour.

The cited reason is "speed optimizations":
https://docs.python.org/3/reference/datamodel.html#special-method-lookup

But there may be other reasons as well. __getattr__ and
__getattribute__ are meant to implement *attribute* lookup. Special
methods are best not regarded as attributes (although they can be
looked up as such), but as implementation of class behavior. You'll
note that special methods also aren't resolved in the instance dict,
but only in the class dict; this is viewed as a matter of correctness,
so that special methods work correctly on class objects (invoking the
metaclass) as well as on instances. In some cases there may also be a
chicken-and-egg problem; should Python call __getattribute__ in order
to resolve the __getattribute__ method?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Frozen apps (py2exe, cx_freeze) built with Python 3.5

2015-12-04 Thread Ian Kelly
On Fri, Dec 4, 2015 at 10:21 AM, d...@forestfield.co.uk
 wrote:
> Python 3.5 will not run under Windows XP, but what about applications created 
> using py2exe or cx_freeze under Windows 7, 8 or 10, is there any knowledge of 
> whether they will run under XP?

I wouldn't expect them to. Those bundlers are just packaging up the
Python binary, so they should have all the same problems.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Python-ideas] Using functools.lru_cache only on some arguments of a function

2015-12-04 Thread Ian Kelly
On Fri, Dec 4, 2015 at 2:44 PM, Bill Winslow  wrote:
> This is a question I posed to reddit, with no real resolution:
> https://www.reddit.com/r/learnpython/comments/3v75g4/using_functoolslru_cache_only_on_some_arguments/
>
> The summary for people here is the following:
>
> Here's a pattern I'm using for my code:
>
> def deterministic_recursive_calculation(input, partial_state=None):
> condition = do_some_calculations(input)
> if condition:
> return deterministic_recursive_calculation(reduced_input,
> some_state)
>
> Basically, in calculating the results of the subproblem, the subproblem can
> be calculated quicker by including/sharing some partial results from the
> superproblem. (Calling the subproblem without the partial state still gives
> the same result, but takes substantially longer.)
>
> I want to memoize this function for obvious reasons, but I need the
> lru_cache to ignore the partial_state argument, for its value does not
> affect the output, only the computation expense.
>
> Is there any reasonable way to do this?

What form does the partial_state take? Would it be reasonable to
design it with __eq__ and __hash__ methods so that each partial state
(or a wrapper of it) is considered equal?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 'string.join' is wrong in my Python console

2015-12-03 Thread Ian Kelly
On Thu, Dec 3, 2015 at 9:00 AM, Robin Koch  wrote:
> Now *I* am confused.
>
> Shouldn't it be
>
> ", ".join(['1', '2', '4', '8', '16'])
>
> instead? Without any importing?

That would be the normal way to write it. The FAQ entry is suggesting
the string module function as an alternative for those who can't
accept it as a string method.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: static variables

2015-12-02 Thread Ian Kelly
On Wed, Dec 2, 2015 at 7:41 AM, Antoon Pardon
 wrote:
> Op 02-12-15 om 14:11 schreef Steven D'Aprano:
>> On Wed, 2 Dec 2015 10:09 pm, Antoon Pardon wrote:
>>
>>> If you want your arguments to be taken seriously, then you better should.
>>> If you use an argument when it suits you and ignore it when it doesn't
>>> you are showing you don't really have an argument. You are just showing
>>> your preference and making it sound like an argument.
>> "A foolish consistency is the hobgoblin of little minds."
>
> So? That doesn't show that we are talking about a foolish consistency here.

It's actually the truest use of the quote that I've yet seen on this
list. Emerson was complaining about those who adhere to opinions that
they've expressed in the past solely for the sake of appearing
consistent in their values, which is basically what you're accusing
Steven of not doing.

If you haven't previously read Self-Reliance, I would recommend it as
a good (and short) read.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is Microsoft Windows secretly downloading childporn to your computer ?!

2015-12-02 Thread Ian Kelly
On Wed, Dec 2, 2015 at 10:36 AM, Keith Thompson  wrote:
> Juha Nieminen  writes:
>> In comp.lang.c++ Steve Hayes  wrote:
>>> You download things FROM a computer, you upload them TO a computer.
>>
>> It's a matter of perspective. If a hacker breaks into your computer and
>> starts a download from somewhere else into your computer, isn't the hacker
>> "downloading" things to your computer?
>
> My understanding of the word "downloading" has always been STOP FEEDING
> THE TROLL!

In what way is discussion of a tangential topic feeding the troll?
Said troll is not even participating in the discussion.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: HELP PLEASE printing single characters!

2015-12-02 Thread Ian Kelly
On Wed, Dec 2, 2015 at 1:44 PM, Dylan Riley  wrote:
> hi ian what would be the correct code to use in this situation then because 
> as far as i am aware the elements of my list should be printed as whole 
> elements and not just characters of the elements.

order.append(choice)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: static variables

2015-12-02 Thread Ian Kelly
On Wed, Dec 2, 2015 at 9:30 AM, Antoon Pardon
<antoon.par...@rece.vub.ac.be> wrote:
> Op 02-12-15 om 15:15 schreef Ian Kelly:
>> On Wed, Dec 2, 2015 at 7:41 AM, Antoon Pardon
>> <antoon.par...@rece.vub.ac.be> wrote:
>>> Op 02-12-15 om 14:11 schreef Steven D'Aprano:
>>>> On Wed, 2 Dec 2015 10:09 pm, Antoon Pardon wrote:
>>>>
>>>>> If you want your arguments to be taken seriously, then you better should.
>>>>> If you use an argument when it suits you and ignore it when it doesn't
>>>>> you are showing you don't really have an argument. You are just showing
>>>>> your preference and making it sound like an argument.
>>>> "A foolish consistency is the hobgoblin of little minds."
>>> So? That doesn't show that we are talking about a foolish consistency here.
>> It's actually the truest use of the quote that I've yet seen on this
>> list. Emerson was complaining about those who adhere to opinions that
>> they've expressed in the past solely for the sake of appearing
>> consistent in their values, which is basically what you're accusing
>> Steven of not doing.
>
> That is not true. I expect that the next time someone will try to
> argue for private attributes or some such, Steven will be among
> those that will support the "consenting adults" line. This view
> of his, is not in the past, it is for all i know still in the
> present. That his latest expression was in the past, doesn't make
> his view something of the past.
>
> If there was a reason to think he had changed his mind, you would
> have been right. But I see no reason for that.
>
> There is a difference between changing your mind and thus change
> your arguments and using an argument selectively.

A person can hold one opinion in some contexts and an opposing opinion
in others.

"Speak what you think now in hard words, and to-morrow speak what
to-morrow thinks in hard words again, though it contradict every thing
you said to-day."

"There will be an agreement in whatever variety of actions, so they be
each honest and natural in their hour. For of one will, the actions
will be harmonious, however unlike they seem. These varieties are lost
sight of at a little distance, at a little height of thought. One
tendency unites them all. The voyage of the best ship is a zigzag line
of a hundred tacks. See the line from a sufficient distance, and it
straightens itself to the average tendency. Your genuine action will
explain itself, and will explain your other genuine actions. Your
conformity explains nothing. Act singly, and what you have already
done singly will justify you now."
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: HELP PLEASE printing single characters!

2015-12-02 Thread Ian Kelly
On Wed, Dec 2, 2015 at 12:58 PM, Dylan Riley  wrote:
> hi all,
> I have been trying to figure out all day why my code is printing single 
> characters from my list when i print random elements using random.choice the 
> elements in the list are not single characters for example when i print, 
> print(LIST[random.choice]) i get:
> ["e", "x", "a", "m", "p", "l", "e"] when i should get ["example"].

Remember that strings are iterable, and that iterating over strings
results in individual characters. That should give you a clue as to
what's going on.

> my code is:
> #Create a program that prints a list of words in random order.
> #The program should print all the words and not repeat any.
>
> import random
>
> LIST = ["blue ", "red ", "yellow ", "green ", "orange "]
> order = []
>
> print("This game will print a random order of colours")
> print("The list is", LIST)
> input("press enter to start")
>
>
>
> while LIST != []:
> choice = random.choice(LIST)
> order += choice

Addition on a list does concatenation, not appending. So this takes
each element from choice and adds them individually to order.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about split method

2015-12-02 Thread Ian Kelly
On Wed, Dec 2, 2015 at 2:37 PM, Robert  wrote:
> Hi,
>
> I learn split method online. When I try to run the line with ss1 beginning,
> I don't understand why its output of ss1 and ss2. I have check the help
> about split. It looks like that it is a numpy method.
> What is the split method parameter (within "  ") for?
>
>
> Thanks,
>
>
>
> ...
> ss0="1, 2, 4, 8, 16".split(", ")
>
> ss0
> Out[2]: ['1', '2', '4', '8', '16']
>
> ss1="1, 2, 4, 8, 16".split(", ")
>
> ss1
> Out[4]: ['1, 2, 4, 8, 16']
>
> ss2="1, 2, 4, 8, 16".split(",   ")
>
> ss2
> Out[9]: ['1, 2, 4, 8, 16']
>
> help(split)
> Help on function split in module numpy.lib.shape_base:

That's just some random function that you've imported into globals by
doing "from numpy import *" or some such. What you're calling in these
examples is a string method, not a global function.

Try help(str.split)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 3.5.0: python.exe is not a valid Windows 32 application

2015-12-02 Thread Ian Kelly
On Wed, Dec 2, 2015 at 4:09 PM,   wrote:
> Hi.
>
> https://mail.python.org/pipermail/python-dev/2015-July/140823.html
> Python 3.5 was dropped the support Windows XP and 2003.
>
>
>
> It's just an aside, but Python 3.5.1 works on my customized Windows 2000 :P
> http://blog.livedoor.jp/blackwingcat/archives/1917281.html

You may be able to get it to run, but as it is unsupported there may
be features that are broken but not immediately obviously so and will
not be fixed if they are.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Subclassing tuple and introspection

2015-12-02 Thread Ian Kelly
On Wed, Dec 2, 2015 at 4:32 PM, Joseph L. Casale
 wrote:
> I need to return a collection of various types, since python doesn't
> have the terse facility of extension methods like C#, subclassing tuple
> and adding a method seems like a terse way to accommodate this.

If you're not already familiar with collections.namedtuple, have a
look at it, as it sounds like just naming the fields may be all that
you need. You can also subclass it further to add methods if desired.

> However, if the method returns one element of the collection, how can
> one enable introspection for users of IDE's that the resulting reference
> is of type A, and therefor has A's fields?
>
> For example:
> col = (Class(..), Class(...))
> item = col[0]
>
> Introspection will now enumerate item as an instance of Class, providing
> its fields. The subclass of tuple breaks this.
>
> Is there a better way to do this?

I think that's going to depend heavily on the specific IDE being used,
but for general usage you might consider using PEP 484 type
annotations; I know that at least PyCharm supports their use for type
hinting.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is Microsoft Windows secretly downloading childporn to your computer ?!

2015-12-01 Thread Ian Kelly
On Tue, Dec 1, 2015 at 12:49 PM, Steve Hayes  wrote:
> On Tue, 1 Dec 2015 03:19:39 +0100, "Skybuck Flying"
>  wrote:
>
>>Hello,
>>
>>The question is:
>>
>>Is Microsoft Windows secretly downloading childporn to your computer ?!
>
> You download things FROM a computer, you upload them TO a computer.

You download things FROM one computer to another. You upload things
from one computer TO another. The only semantic difference is in which
end of the transfer is "local". Otherwise, it's like saying "up the
street" versus "down the street", so what difference does it make?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Could you explain this rebinding (or some other action) on "nums = nums"?

2015-12-01 Thread Ian Kelly
On Tue, Dec 1, 2015 at 2:32 PM, Denis McMahon  wrote:
> On Tue, 01 Dec 2015 03:32:31 +, MRAB wrote:
>
>> In the case of:
>>
>>  tup[1] += [6, 7]
>>
>> what it's trying to do is:
>>
>>  tup[1] = tup[1].__iadd__([6, 7])
>>
>> tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but
>> then Python tries to put the result that the method returns into tup[1].
>> That fails because tup itself is a tuple, which is immutable.
>
> I think I might have found a bug:
>
> $ python
> Python 2.7.3 (default, Jun 22 2015, 19:33:41)
> [GCC 4.6.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 tup = [1,2,3],[4,5,6]
 tup
> ([1, 2, 3], [4, 5, 6])
 tup[1]
> [4, 5, 6]
 tup[1] += [7,8,9]
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'tuple' object does not support item assignment
 tup[1]
> [4, 5, 6, 7, 8, 9]
 tup
> ([1, 2, 3], [4, 5, 6, 7, 8, 9])
 quit()

No, that's the expected result. As MRAB wrote, the list *is* mutated
when its __iadd__ method is called. The TypeError happens afterward
when the assignment is attempted.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "Downloading"

2015-12-01 Thread Ian Kelly
On Tue, Dec 1, 2015 at 5:05 PM, Chris Angelico  wrote:
> On Wed, Dec 2, 2015 at 6:05 AM, Random832  wrote:
>> On 2015-12-01, Steve Hayes  wrote:
>>> You download things FROM a computer, you upload them TO a computer.
>>
>> I'm a little bit confused as to what kinds of file transfers
>> you think don't have at least two endpoints.
>
> From some other computer to the one you're controlling it from. A
> download is initiated by the recipient; an upload is initiated by the
> sender.

What about transfers that are initiated by neither?

scp remote_host1:path/to/file remote_host2:path/to/destination
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Ian Kelly
On Dec 1, 2015 1:36 PM, "Rick Johnson"  wrote:

>

> On Tuesday, December 1, 2015 at 1:55:59 AM UTC-6, Steven D'Aprano wrote:

> > Python was never intended to be "merely" a teaching language. I think

> > Guido's original vision was for it to be a glue language between C

> > libraries, and a scripting language.

>

> It's a well know fact that GvR was inspired to create Python from his
experiences working with a language called ABC -- and ABC was designed
*EXCLUSIVELY* to be a beginners language.

Which is exactly what made ABC itself unsuitable for Guido's purpose, which
was to create an *applications* language with better productivity than C to
support users of Amoeba, the OS that he was working on at the time.

> I am not arguing that "abstractions are evil", no, my position is that
abstractions must be constructed in a manner that provides a clear trail of
bread crumbs which lead to the underlying processes. With print, not only
is the engine in another dimension, but the hood is as well! How is a noob
to discover the engine when he cannot find the hood?

>

> Ponder the following example code (as a noob!):

>

>  stdout.write("Dude, i found my car, the hood, and the effing engine!!!")

>

> Even a noob can intuit what is going on here. First we have an *OBJECT*
named "stdout, and we can extrapolate that stdout is an abbreviation for
StandardOutput. Next, we see a method called "write", and, if our IQ is
above room temperature, then we can extrapolate what that method will do.

This is absurd. You postulate a beginner so rank that they can't understand
what "print" means, yet you expect them to intuitively know:

1) what an object is;

2) what a method is;

3) that a method is identified by placing a period between the object and
the name of the method;

4) what "output" is in the context of programming;

5) and not be confused about what makes the output "standard".

> Now ponder this code (as a noob!):

>

>  print("Dude, where's the intuitiveness?")

>

> What the heck does print do? Where will the string go after i execute
this line of code? Should i turn my printer on? Should i check my ink
levels? And what OEM drivers are required?

You're describing this as if your hypothetical beginner were learning
Python in a vacuum. In reality, people learn from a teacher, or a book, or
at minimum a tutorial.

Here's how you teach somebody what "print" does: instruct them to type
print("hello world") at the interactive prompt. Note that Python writes
"hello world" as a result. If they really want, they can check their
printer and see that nothing came out. That's it. The student now
understands what "print" means.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about code writing '% i, callback'

2015-12-01 Thread Ian Kelly
On Mon, Nov 30, 2015 at 7:44 PM, Dennis Lee Bieber
 wrote:
> On Mon, 30 Nov 2015 10:55:23 -0800 (PST), fl  declaimed
> the following:
>
>>Thanks Ian. I created the class because I want to use the original example
>>line
>>
>> UI.Button("button %s" % i, callback)
>>
>>Is there another way to use the above line without my class definition?
>>I do feel that my created class does not match well with the above line
>>because the first item "button %s" does not fit __self__ in the class.
>
> The first item passed to a method call is the instance object... In
> this case, whatever "UI" is bound to.
>
> If it helps, think of
>
> UI.Button("string", callback)
> as
> Button(UI, "string", callback)

This is only correct if "UI" is bound to an instance of a class and
"Button" is a method of that class. If UI is a class itself or a
module, then those are not equivalent.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about code writing '% i, callback'

2015-11-30 Thread Ian Kelly
On Mon, Nov 30, 2015 at 10:44 AM, fl  wrote:
> I come across the following code snippet.
>
> for i in range(10):
> def callback():
> print "clicked button", i
> UI.Button("button %s" % i, callback)
>
> The content inside parenthesis in last line is strange to me.
>
> "button %s" % i, callback

These are the arguments being passed to UI.Button. The first argument is:

"button %s" % i

This is an example of printf-style string formatting. See the link
that Zachary posted.

The second argument is the function named callback.

> That is, the writing looks like recognized as three items when I try with a
> class definition (it can run with this):
>
> class buibutton():
> print 'sd'
> def __nonzero__(self):
>return False
>
> def Button(str, ii, callbackk):
>
> return
>
>
> Could you explain it to me?

How is this related to the example above?

Here, Button is defined as a method of a class. Since it's a method,
the first parameter is the "self" parameter, which will implicitly
take the value of the class instance that you're calling the Button
method on. If you're trying to call this like above, then the second
parameter "ii" will take the value of the string from the example
above, and callbackk will take the value of the callback argument from
above.

Thus, the method that you've defined has three parameters but only
takes two explicit arguments.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about code writing '% i, callback'

2015-11-30 Thread Ian Kelly
On Mon, Nov 30, 2015 at 10:36 AM, fl  wrote:
> Thanks for the replies. Now, I have the following code:
>
>
>
> class buibutton():
> print 'sd'
> def __nonzero__(self):
>return False
>
> def Button(self, ii, callbackk):
> callbackk()
> return
> UI=buibutton()
>
>
> for i in range(10):
> def callback():
> print "clicked button", i
> UI.Button("button %s" % i, callback)
>
>
> To my surprise, the output is not the original link expected. i.e. it is
> the same with binding to the current values:

The callback function is being called immediately, in the body of the
loop, not stored and called later. The value of i in the closure has
not actually changed yet at the point you're calling it. If you
instead store the callback and call it later, you'll find that each
message says "button 9".
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-25 Thread Ian Kelly
On Wed, Nov 25, 2015 at 2:05 PM, Antoon Pardon
<antoon.par...@rece.vub.ac.be> wrote:
> Op 25-11-15 om 21:39 schreef Ian Kelly:
>> On Wed, Nov 25, 2015 at 11:27 AM, Antoon Pardon
>> <antoon.par...@rece.vub.ac.be> wrote:
>>> I don't know what you are talking about. The first thing I have argued
>>> is that () is a literal. Then I have expaned that to that something
>>> like (3, 5, 8) is a literal. I never argued that tuple expressions
>>> in general are literals. And one way I supported my point was with the
>>> following quote from the python language reference.
>>>
>>>   Literals are notations for constant values of some built-in types.
>>>
>>> And I think that the things I argued were literals, were in fact
>>> constant values of some built-in type.
>>
>> I believe that sentence from the docs is using "some" to mean "not
>> all", whereas you are apparently using it to mean "any".
>>
>> frozenset([1,2,3]) constructs a constant value of a built-in type.
>> Would you consider that a literal?
>
> I am inclined to say yes, because a sufficient intelligent compilor
> can compute the value and store it do be retrieved and bound to a
> target when needed.

I'm curious then what you think of this:

from collections import namedtuple

class Point(namedtuple("Point", "x y")): pass

Point(17, 12)

Still a constant, but not a built-in type. Would you consider that a literal?
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-25 Thread Ian Kelly
On Wed, Nov 25, 2015 at 5:52 PM, Random832  wrote:
> On 2015-11-25, Ben Finney  wrote:
>> That is, the ‘2’ in ‘cartesian_point = (2, 3)’ means something different
>> than in ‘cartesian_point = (3, 2)’.
>>
>> Whereas the ‘2’ in ‘test_scores = [2, 3]’ means exactly the same as in
>> ‘test_scores = [3, 2]’.
>>
>> If each position in the sequence gives the value there a different
>> menaning, use a tuple; if not, use a list.
>
> I don't think that's really right. The absence of first-class
> multisets in python does mean that lists get "abused" for that
> purpose, but I don't think that means that there's no legitimate
> use-case for a list (i.e. a mutable sequence in which position is
> significant).
>
> The difference between a tuple and a list is that one is mutable
> and the other is not. The difference you are describing is
> between a list and a multiset (or a tuple and an immutable
> multiset).

I think that Ben was actually trying to make a distinction between
heterogeneity and homogeneity of the contents, not a distinction of
whether the collection was ordered or not. You can of course have a
homogeneous collection for which order is still important, e.g. a
batting line-up.
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-25 Thread Ian Kelly
On Wed, Nov 25, 2015 at 7:25 PM, Chris Angelico  wrote:
> On Thu, Nov 26, 2015 at 1:08 PM, Alan Bawden  wrote:
>> (Note that nothing in the documentation I can find actually _guarantees_
>> that a Python implementation will only have one unique empty tuple, but
>> I wouldn't be suprised if the following is nonetheless true in all
>> current implementations:
>>
>>>>> tuple([]) is tuple([])
>>True
>>
>> )
>
> Jython 2.5.3 (, Oct 8 2014, 03:39:09)
> [OpenJDK 64-Bit Server VM (Oracle Corporation)] on java1.7.0_85
> Type "help", "copyright", "credits" or "license" for more information.
 tuple([]) is tuple([])
> False
>
> Python 2.7.8 (2.4.0+dfsg-3, Dec 20 2014, 13:30:46)
> [PyPy 2.4.0 with GCC 4.9.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> tuple([]) is tuple([])
> False

Well, he did say all "current" implementations. CPython 2.7 may still
be supported, but that doesn't make it current. And anything at 2.5 is
just archaic.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: list slice and generators

2015-11-25 Thread Ian Kelly
On Wed, Nov 25, 2015 at 10:44 AM, Ian Kelly <ian.g.ke...@gmail.com> wrote:
> On Wed, Nov 25, 2015 at 3:07 AM, Peter Otten <__pete...@web.de> wrote:
>>> elif name in METRICS_AVG:
>>   # writing a function that calculates the average without
>>   # materialising the list left as an exercise ;)
>
> metrics = itertools.tee(metrics)
> return int(sum(metrics[0]) / len(metrics[1]))

Actually, don't do that. It does effectively materialize the list,
just not as a list.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: list slice and generators

2015-11-25 Thread Ian Kelly
On Wed, Nov 25, 2015 at 3:07 AM, Peter Otten <__pete...@web.de> wrote:
> to get down to one intermediate list. Avoiding the last one is a bit tricky:
>
> metrics = (converter(x.metric(name)) for x in self._server_per_proc)
> metrics = (x for x in metrics if x is not None)
> try:
> # if there is at least one item the generator is not empty
> first = next(metrics)
> except StopIteration:
> metrics = ()
> else:
> # put the first item back in
> metrics = itertools.chain([first], metrics)
> assert metrics

metrics is always going to be an itertools.chain object at this
assert, so how could the assertion ever fail?

>> elif name in METRICS_AVG:
>   # writing a function that calculates the average without
>   # materialising the list left as an exercise ;)

metrics = itertools.tee(metrics)
return int(sum(metrics[0]) / len(metrics[1]))
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-25 Thread Ian Kelly
On Wed, Nov 25, 2015 at 11:27 AM, Antoon Pardon
 wrote:
> I don't know what you are talking about. The first thing I have argued
> is that () is a literal. Then I have expaned that to that something
> like (3, 5, 8) is a literal. I never argued that tuple expressions
> in general are literals. And one way I supported my point was with the
> following quote from the python language reference.
>
>   Literals are notations for constant values of some built-in types.
>
> And I think that the things I argued were literals, were in fact
> constant values of some built-in type.

I believe that sentence from the docs is using "some" to mean "not
all", whereas you are apparently using it to mean "any".

frozenset([1,2,3]) constructs a constant value of a built-in type.
Would you consider that a literal?

How about tuple(1, 2+3, abs(-19))? Still a constant value of a built-in type.

I think the most important word in the definition you quoted is
actually "notation". It says it right there: literals are not
"constant values", but notations for *expressing* constant values.

The tuple display notation expresses values that may be constant but
need not be. Therefore it's not a literal notation.
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-25 Thread Ian Kelly
On Wed, Nov 25, 2015 at 10:18 AM, BartC  wrote:
>> We have no way of evaluating their power or simplicity,
>> since they are not available to us.
>
> I'll see if I can rustle up a comparison so that Python users can see what
> they're missing!

Unless you're going to make the actual languages available for public
use, what's the point?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Bi-directional sub-process communication

2015-11-24 Thread Ian Kelly
On Mon, Nov 23, 2015 at 10:25 PM, Cameron Simpson  wrote:
> Then #3. I would have a common function/method for submitting a request to
> go to the subprocess, and have that method return an Event on which to wait.
> Then caller then just waits for the Event and collects the data. Obviously,
> the method does not just return the Event, but an Event and something to
> receive the return data. I've got a class called a Result for this kind of
> thing; make a small class containing an Event and which will have a .result
> attribute for the return information; the submitting method allocates one of
> these and returns it. The response handler gets the instance (by looking it
> up from the tag), sets the .result attribute and fires the Event. Your
> caller wakes up from waiting on the Event and consults the .result
> attribute.

Your Result sounds suspiciously like a Future. ;-)
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-24 Thread Ian Kelly
On Tue, Nov 24, 2015 at 1:54 PM, Antoon Pardon
<antoon.par...@rece.vub.ac.be> wrote:
> Op 24-11-15 om 20:15 schreef Ian Kelly:
>
>>> But no matter what you want to call it. The dis module shows that
>>> -42 is treated in exactly the same way as 42, which is treated
>>> exactly the same way as () or as (5, 8, 13) which is treated
>>> differently from [] or [5, 8, 13].
>>
>> This is an implementation detail. The compiler would also be free to
>> compile -42 into byte code as the negation of the constant 42. That 42
>> is a literal, on the other hand, is part of the language
>> specification.
>
> I think you are picking nits.

Yes. This entire subtopic about literals is picking nits. :-)
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-24 Thread Ian Kelly
On Tue, Nov 24, 2015 at 9:41 AM, Antoon Pardon
 wrote:
> Op 24-11-15 om 16:48 schreef Chris Angelico:
>> () is not a literal either.
>
> The byte code sure suggests it is.
>
> Take the following code:
>
> import dis
>
> def f():
>   i = 42
>   t = ()
>   l = []
>
> dis.dis(f)
>
> That produces the following:
>
>
>   4   0 LOAD_CONST   1 (42)
>   3 STORE_FAST   0 (i)
>
>   5   6 LOAD_CONST   2 (())
>   9 STORE_FAST   1 (t)
>
>   6  12 BUILD_LIST   0
>  15 STORE_FAST   2 (l)
>  18 LOAD_CONST   0 (None)
>  21 RETURN_VALUE

I'm not sure what this is meant to prove. None is clearly an
identifier, not a literal, and it also gets treated as a constant in
the code above.

> So on what grounds would you argue that () is not a literal.

This enumerates exactly what literals are in Python:

https://docs.python.org/3/reference/lexical_analysis.html#literals

I think it's a rather pedantic point, though. How are nuances of the
grammar at all related to user expectations?
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-24 Thread Ian Kelly
On Tue, Nov 24, 2015 at 10:32 AM, Antoon Pardon
<antoon.par...@rece.vub.ac.be> wrote:
> Op 24-11-15 om 17:56 schreef Ian Kelly:
>
>>
>>> So on what grounds would you argue that () is not a literal.
>>
>> This enumerates exactly what literals are in Python:
>>
>> https://docs.python.org/3/reference/lexical_analysis.html#literals
>>
>> I think it's a rather pedantic point, though. How are nuances of the
>> grammar at all related to user expectations?
>>
>
> I think that enumaration is too limited. The section starts with:
>
>Literals are notations for constant values of some built-in types.
>
> () satisfies that definition, which is confirmed by the byte code
> produced for it.

Literals are a type of lexical token. All of the literals shown in
that section are, indeed, tokens. Now I would point you to the grammar
specification:

https://docs.python.org/3/reference/grammar.html

And specifically the "atom" rule, which defines both list displays and
list comprehensions (as well as literals) as being atoms.
Specifically, it parses () as the token '(', followed by an optional
yield_expr or testlist_comp, followed by the token ')'. In no way is
that a single token, nor therefore a literal.
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-24 Thread Ian Kelly
On Tue, Nov 24, 2015 at 10:53 AM, Ian Kelly <ian.g.ke...@gmail.com> wrote:
> On Tue, Nov 24, 2015 at 10:32 AM, Antoon Pardon
> <antoon.par...@rece.vub.ac.be> wrote:
>> Op 24-11-15 om 17:56 schreef Ian Kelly:
>>
>>>
>>>> So on what grounds would you argue that () is not a literal.
>>>
>>> This enumerates exactly what literals are in Python:
>>>
>>> https://docs.python.org/3/reference/lexical_analysis.html#literals
>>>
>>> I think it's a rather pedantic point, though. How are nuances of the
>>> grammar at all related to user expectations?
>>>
>>
>> I think that enumaration is too limited. The section starts with:
>>
>>Literals are notations for constant values of some built-in types.
>>
>> () satisfies that definition, which is confirmed by the byte code
>> produced for it.
>
> Literals are a type of lexical token. All of the literals shown in
> that section are, indeed, tokens. Now I would point you to the grammar
> specification:
>
> https://docs.python.org/3/reference/grammar.html
>
> And specifically the "atom" rule, which defines both list displays and
> list comprehensions (as well as literals) as being atoms.
> Specifically, it parses () as the token '(', followed by an optional
> yield_expr or testlist_comp, followed by the token ')'. In no way is
> that a single token, nor therefore a literal.

In case reading the grammar doesn't convince, we can also get this
result from playing with the language:

>>> import tokenize
>>> from io import StringIO
>>> list(tokenize.generate_tokens(StringIO('()').readline))
[TokenInfo(type=52 (OP), string='(', start=(1, 0), end=(1, 1),
line='()'), TokenInfo(type=52 (OP), string=')', start=(1, 1), end=(1,
2), line='()'), TokenInfo(type=0 (ENDMARKER), string='', start=(2, 0),
end=(2, 0), line='')]

Two separate tokens of the OP type.

>>> list(tokenize.generate_tokens(StringIO('42').readline))
[TokenInfo(type=2 (NUMBER), string='42', start=(1, 0), end=(1, 2),
line='42'), TokenInfo(type=0 (ENDMARKER), string='', start=(2, 0),
end=(2, 0), line='')]

One token, of a literal type.

>>> list(tokenize.generate_tokens(StringIO('(1,2,3)').readline))
[TokenInfo(type=52 (OP), string='(', start=(1, 0), end=(1, 1),
line='(1,2,3)'), TokenInfo(type=2 (NUMBER), string='1', start=(1, 1),
end=(1, 2), line='(1,2,3)'), TokenInfo(type=52 (OP), string=',',
start=(1, 2), end=(1, 3), line='(1,2,3)'), TokenInfo(type=2 (NUMBER),
string='2', start=(1, 3), end=(1, 4), line='(1,2,3)'),
TokenInfo(type=52 (OP), string=',', start=(1, 4), end=(1, 5),
line='(1,2,3)'), TokenInfo(type=2 (NUMBER), string='3', start=(1, 5),
end=(1, 6), line='(1,2,3)'), TokenInfo(type=52 (OP), string=')',
start=(1, 6), end=(1, 7), line='(1,2,3)'), TokenInfo(type=0
(ENDMARKER), string='', start=(2, 0), end=(2, 0), line='')]

Two tokens for the parentheses, plus three literal tokens for the
ints, plus two more tokens for the separating commas. Definitely not a
literal.

Credit to Steven for using this approach to make a similar point about
literals in a previous thread.
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-24 Thread Ian Kelly
On Tue, Nov 24, 2015 at 11:45 AM, Antoon Pardon
 wrote:
> I think limiting literals to lexical tokens is too limited. Sure we
> can define them like that in the context of the python grammar, but
> I don't see why we should limit ourselves to such a definition outside
> that context.
>
> I see nothing wrong with regarding -42 as a literal while according
> to the python grammar it isn't.
>
> There is nothing wrong with the notion that a literal can be a
> compounded value.

I'm somewhat inclined to agree with this. Taking an example from
another language, if you use Javascript you'll hear all the time about
"object literals" or "object literal notation". If you read the
ECMAScript spec, however, you won't find the phrase "object literal"
in there once. It seems that the common usage of "literal" is not the
same as the way it's used in formal writing of language
specifications.

> But no matter what you want to call it. The dis module shows that
> -42 is treated in exactly the same way as 42, which is treated
> exactly the same way as () or as (5, 8, 13) which is treated
> differently from [] or [5, 8, 13].

This is an implementation detail. The compiler would also be free to
compile -42 into byte code as the negation of the constant 42. That 42
is a literal, on the other hand, is part of the language
specification.
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-24 Thread Ian Kelly
On Tue, Nov 24, 2015 at 12:00 PM, Random832  wrote:
> On 2015-11-24, Chris Angelico  wrote:
>> Probably the grammar. In other words, it's part of the language's very
>> definition.
>
> Then the definition is wrong. I think "literal" is a word whose meaning is
> generally agreed on, rather than something each language's spec can invent 
> from
> whole cloth for itself. It's not a python term, it's a programming term.

The Python language spec uses the word the same way that other
language specs do. Is it the spec's usage that is wrong, or the common
understanding of it?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Bi-directional sub-process communication

2015-11-23 Thread Ian Kelly
On Mon, Nov 23, 2015 at 10:54 AM, Israel Brewster  wrote:
> Concern: Since the master process is multi-threaded, it seems likely enough 
> that multiple threads on the master side would make requests at the same 
> time. I understand that the Queue class has locks that make this fine (one 
> thread will complete posting the message before the next is allowed to 
> start), and since the child process only has a single thread processing 
> messages from the queue, it should process them in order and post the 
> responses (if any) to the master_queue in order. But now I have multiple 
> master processes all trying to read master_queue at the same time. Again, the 
> locks will take care of this and prevent any overlapping reads, but am I 
> guaranteed that the threads will obtain the lock and therefore read the 
> responses in the right order? Or is there a possibility that, say, thread 
> three will get the response that should have been for thread one? Is this 
> something I need to take into consideration, and if so, how?

Yes, if multiple master threads are waiting on the queue, it's
possible that a master thread could get a response that was not
intended for it. As far as I know there's no guarantee that the
waiting threads will be woken up in the order that they called get(),
but even if there are, consider this case:

Thread A enqueues a request.
Thread B preempts A and enqueues a request.
Thread B calls get on the response queue.
Thread A calls get on the response queue.
The response from A's request arrives and is given to B.

Instead of having the master threads pull objects off the response
queue directly, you might create another thread whose sole purpose is
to handle the response queue. That could look like this:


request_condition = threading.Condition()
response_global = None

def master_thread():
global response_global
with request_condition:
request_queue.put(request)
request_condition.wait()
# Note: the Condition should remain acquired until
response_global is reset.
response = response_global
response_global = None
if wrong_response(response):
raise RuntimeError("got a response for the wrong request")
handle_response(response)

def response_thread():
global response_global
while True:
response = response_queue.get()
with request_condition:
response_global = response
request_condition.notify()


As another option you could use a multiprocessing.Manager to
coordinate passing the response back more directly, but starting a
third process seems like overkill for this.
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-23 Thread Ian Kelly
On Mon, Nov 23, 2015 at 1:23 AM, Chris Angelico  wrote:
> def latearg(f):
> tot_args = f.__code__.co_argcount
> min_args = tot_args - len(f.__defaults__)
> defs = f.__defaults__
> # With compiler help, we could get the original text as well as something
> # executable that works in the correct scope. Without compiler help, we
> # either use a lambda function, or an exec/eval monstrosity that can't use
> # the scope of its notional definition (since its *actual* definition will
> # be inside this decorator). Instead, just show a fixed bit of text.

You should be able to get the correct globals from f.__globals__.

For locals, the decorator might capture the locals of the previous
stack frame at the moment the decorator was called, but that's
potentially a pretty heavy thing to be retaining for this purpose; the
definition of a @latearg function would indefinitely keep a reference
to every single object that was bound to a variable in that scope, not
just the things it needs. For better specificity you could parse the
expression and then just grab the names that it uses. Even so, this
would still act somewhat like early binding in that it would reference
the local variables at the time of definition rather than evaluation.

Nonlocals? Just forget about it.

> This does implement late binding, but:
> 1) The adornment is the rather verbose "lambda:", where I'd much
> rather have something shorter
> 2) Since there's no way to recognize "the ones that were adorned", the
> decorator checks for "anything callable"

A parameter annotation could be used in conjunction with the decorator.

@latearg
def x(y: latearg = lambda: []):
...

But that's even more verbose. In the simple case where all the
defaults should be late, one could have something like:

@latearg('*')
def x(y=lambda: []):
...

The argument could be generalized to pass a set of parameter names as
an alternative to the annotation.

> 3) Keyword args aren't handled - they're passed through as-is (and
> keyword-only arg defaults aren't rendered)

I would expect that Python 3 Signature objects would make this a lot
simpler to handle.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Bi-directional sub-process communication

2015-11-23 Thread Ian Kelly
On Mon, Nov 23, 2015 at 12:55 PM, Ian Kelly <ian.g.ke...@gmail.com> wrote:
> On Mon, Nov 23, 2015 at 10:54 AM, Israel Brewster <isr...@ravnalaska.net> 
> wrote:
>> Concern: Since the master process is multi-threaded, it seems likely enough 
>> that multiple threads on the master side would make requests at the same 
>> time. I understand that the Queue class has locks that make this fine (one 
>> thread will complete posting the message before the next is allowed to 
>> start), and since the child process only has a single thread processing 
>> messages from the queue, it should process them in order and post the 
>> responses (if any) to the master_queue in order. But now I have multiple 
>> master processes all trying to read master_queue at the same time. Again, 
>> the locks will take care of this and prevent any overlapping reads, but am I 
>> guaranteed that the threads will obtain the lock and therefore read the 
>> responses in the right order? Or is there a possibility that, say, thread 
>> three will get the response that should have been for thread one? Is this 
>> something I need to take into consideration, and if so, how?
>
> Yes, if multiple master threads are waiting on the queue, it's
> possible that a master thread could get a response that was not
> intended for it. As far as I know there's no guarantee that the
> waiting threads will be woken up in the order that they called get(),
> but even if there are, consider this case:
>
> Thread A enqueues a request.
> Thread B preempts A and enqueues a request.
> Thread B calls get on the response queue.
> Thread A calls get on the response queue.
> The response from A's request arrives and is given to B.
>
> Instead of having the master threads pull objects off the response
> queue directly, you might create another thread whose sole purpose is
> to handle the response queue. That could look like this:
>
>
> request_condition = threading.Condition()
> response_global = None
>
> def master_thread():
> global response_global
> with request_condition:
> request_queue.put(request)
> request_condition.wait()
> # Note: the Condition should remain acquired until
> response_global is reset.
> response = response_global
> response_global = None
> if wrong_response(response):
> raise RuntimeError("got a response for the wrong request")
> handle_response(response)
>
> def response_thread():
> global response_global
> while True:
> response = response_queue.get()
> with request_condition:
> response_global = response
> request_condition.notify()

Actually I realized that this fails because if two threads get
notified at about the same time, they could reacquire the Condition in
the wrong order and so get the wrong responses.

Concurrency, ugh.

It's probably better just to have a Condition/Event per thread and
have the response thread identify the correct one to notify, rather
than just notify a single shared Condition and hope the threads wake
up in the right order.
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-21 Thread Ian Kelly
On Sat, Nov 21, 2015 at 1:46 AM, Chris Angelico  wrote:
> On Sat, Nov 21, 2015 at 7:38 PM, Todd  wrote:
>> Rather than a dedicated syntax, might this be something that could be
>> handled by a built-in decorator?
>>
>> Maybe something like:
>>
>> @late_binding
>> def myfunc(x, y=[]):
>
> No, it can't; by the time the decorator runs, the expression has
> already been evaluated. Without syntax, this can only be done with
> gross hacks like lambda functions.
>
> It could be done thus:
>
> @late_binding
> def myfunc(x, y=lambda: []):
>
> and then the decorator could wrap the function. I'm not entirely sure
> I could implement it reliably, but even leaving that aside, having to
> put "lambda:" in front of everything is pretty ugly.

Note that "lambda: []" can also be spelled "list".
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-20 Thread Ian Kelly
On Fri, Nov 20, 2015 at 9:24 AM, Chris Angelico  wrote:
> The cases where that's not true are usually ones that are more like
> C++ overloaded functions:
>
> def next(iter):
> return iter.__next__()
> def next(iter, default):
> try: return iter.__next__()
> except StopIteration: return default

IMO the version with the default argument should have a different
name, as it is conceptually a different function.
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-20 Thread Ian Kelly
On Fri, Nov 20, 2015 at 5:39 AM, BartC  wrote:
> * The persistent nonsense that somehow [] is mutable (what happens is that
> [] is assigned to a variable, and /that/ is mutable) (And I will probably
> get some flak now because 'assign' and 'variable' are meaningless in
> Python!)

I think the problem here is that you're talking as if [] is a unique
value, which it isn't. [] is a list display that *constructs* a list,
not a list itself.
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-20 Thread Ian Kelly
On Fri, Nov 20, 2015 at 5:28 AM, Marko Rauhamaa  wrote:
> The Ackermann function really is an esoteric example, but the other
> example that has been discussed here can make practical use of the
> default-value semantics:
>
>[ lambda x: i * x for i in range(4) ]
>
> which is salvaged with a default value:
>
>[ lambda x, i=i: i * x for i in range(4) ]
>
> or, more hygienically:
>
>[ (lambda i=i: lambda x: i * x)() for i in range(4) ]

Note that this last version could be rewritten as:

[ (lambda i: lambda x: i * x)(i) for i in range(4) ]

At which point the default value semantics are no longer needed.

> One could argue that you should always use a sentinel object for default
> values. That also allows you to distinguish between omitted values and
> default values:
>
>def asklist(caption, data, n=omitted, rows=omitted, width=omitted,
>flags=omitted, buttons=omitted, tablist=omitted,
>heading=omitted):
>
> but that would be rather pedantic in most circumstances.

I think that would be bad design; in general, you shouldn't *need* to
distinguish whether the value was omitted, because it should always be
possible to explicitly pass the default value.
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2015-11-20 Thread Ian Kelly
On Fri, Nov 20, 2015 at 9:31 AM, Marko Rauhamaa <ma...@pacujo.net> wrote:
> Ian Kelly <ian.g.ke...@gmail.com>:
>
>> On Fri, Nov 20, 2015 at 5:28 AM, Marko Rauhamaa <ma...@pacujo.net> wrote:
>>> One could argue that you should always use a sentinel object for
>>> default values. That also allows you to distinguish between omitted
>>> values and default values:
>>>
>>>def asklist(caption, data, n=omitted, rows=omitted, width=omitted,
>>>flags=omitted, buttons=omitted, tablist=omitted,
>>>heading=omitted):
>>>
>>> but that would be rather pedantic in most circumstances.
>>
>> I think that would be bad design; in general, you shouldn't *need* to
>> distinguish whether the value was omitted, because it should always be
>> possible to explicitly pass the default value.
>
> Consider the mutator pattern:
>
> def name(self, value=omitted):
> if value is omitted:
> return self._name
> self._name = value
>
> https://en.wikipedia.org/wiki/Mutator_method#C.2B.2B_example>

Why would you ever want to do this in a language with properties?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How To Create A Endles List Of Lists In Python...???

2015-11-20 Thread Ian Kelly
On Fri, Nov 20, 2015 at 11:16 AM,   wrote:
> Dana petak, 20. studenoga 2015. u 18:16:52 UTC+1, korisnik Denis McMahon 
> napisao je:
>> On Fri, 20 Nov 2015 08:43:04 +0100, HKRSS wrote:
>>
>> > Thanks In Advance, Robert...;)
>>
>> Just keep appending child lists to parent list:
>>
>> l = []
>>
>> while True:
>>l.append([])
>>
>> Until you run out of memory
>>
>> But I think that this answer although it appears accurate to the question
>> is not a solution for anything useful, because it will just use all the
>> memory up. So perhaps you need to express your question in a better
>> manner.
>>
>> --
>> Denis McMahon, denismfmcma...@gmail.com
>
> I Think That LISP Is Only Solution, I Wil Give Up Frpm Python...

Nagy and Chris gave you two different perfectly good solutions for Python.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: error help import random

2015-11-20 Thread Ian Kelly
On Fri, Nov 20, 2015 at 10:57 AM, Peter Otten <__pete...@web.de> wrote:
> Dylan Riley wrote:
>
>> input("\nPress enter to see your fortune")
>
> Make sure that you run your code with Python 3, not Python 2.

Or if you must use Python 2, use raw_input() instead of input().

>> fortune = random.randrange(6) + 1

Also, you have an off-by-one error here. randrange(6) will give you an
integer between 0 and 5, inclusive (a total of 6 possible values).
Adding 1 will then result in an integer between 1 and 6, inclusive,
but you don't have a case for a value of 6.
-- 
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 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 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: 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


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


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

2015-11-18 Thread Ian Kelly
On Wed, Nov 18, 2015 at 5:34 PM, fl  wrote:
> After I try with
>
> list1 = eList(12, [2])
>
> and
>
> list1 = eList(12)
>
> it gives me new surprises. Even though I delete list1, the subsequent
> list1 = eList(12)
> will remember the number of '12' of the previous sequence. This is my new
> question: What does 'del' do? It does not look like a thorough list deletion
>  from the effect.

It just deletes the variable list1, i.e. it unbinds the value from the
name. It does nothing at all to the list that was bound, as other
variables may still be bound to it.

The core issue is that the default value of your eList function is
always the same list. Assigning that list to a variable and then
unassigning it is not going to change that.
-- 
https://mail.python.org/mailman/listinfo/python-list


<    3   4   5   6   7   8   9   10   11   12   >