Re: what does 'a=b=c=[]' do

2011-12-21 Thread alex23
On Dec 22, 8:25 am, Eric  wrote:
> This surprises me, can someone tell me why it shouldn't?  I figure if
> I want to create and initialize three scalars the just do "a=b=c=7",
> for example, so why not extend it to arrays.

The thing to remember is that everything is an object, and that it's
better to think of variables as labels on an object.

So: a=b=c=7 means that _one_ integer object with the value of 7 can be
referenced using any of the labels a, b or c. x=y=z=[] means that
_one_ empty list can be referenced using x, y or z.

The difference is that the value of a number object _cannot be
changed_ ('immutable') while a list can be modified to add or remove
items ('mutable'). a=10 just reassigns the label a to an integer
object of value 10. x.append("foo") _modifies_ the list referred to by
x, which is the same list known as y & z.

> Also, is there a more pythonic way to do "x=[], y=[], z=[]"?

I'd say that _is_ the most pythonic way, it's very obvious in its
intent (or would be with appropriate names). If it bothers you that
much:

def listgen(count, default=[]):
for _ in xrange(count):
yield default[:]

x, y, z = listgen(3)

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


Re: Elementwise -//- first release -//- Element-wise (vectorized) function, method and operator support for iterables in python.

2011-12-20 Thread alex23
On Dec 21, 10:24 am, Nathan Rice 
wrote:
> The idea is to provide a syntax that lets you do very complex things
> on collections in a more readable manner, without having 5 or 6 lines
> of generator expressions.

Have you seen PyLINQ? It has a similar approach to operating on
collections, returning a PyLINQ object after each call to facilitate
chaining. https://github.com/kalessin/PyLINQ/blob/master/pylinq/linq.py

This is a personal opinion on the code, but I'd move instantiating the
new ElementwiseProxy out of each method and into its own decorator:

# declare this outside of the class
def chainable(fn):
def _(self, *args, **kwargs):
return ElementwiseProxy(fn(self, *args, **kwargs), self)
return _

This way, each method that is chainable is a little more obvious
without inspecting the code, and the method body itself is only doing
what the method says it does:

@chainable
def __add__(self, other):
return (e + other for e in object.__getattribute__(self,
"iterable"))

Incidentally, displaying an ElementwiseProxy instance doesn't go down
well with iPython:

In [1]: from elementwise import *

In [2]: e = ElementwiseProxy(['one','two','three'])

In [3]: e
Out[3]: ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (6, 0))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-19 Thread alex23
Steven D'Aprano  wrote:
> Nevertheless, I think the suggested syntax "@list args" is awful.

Yep, and it's the least awful part of the entire proposal.


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


Re: IPython 0.12 is out!

2011-12-19 Thread alex23
On Dec 20, 4:07 am, Wanderer  wrote:
> The windows installer didn't work but installing from the tar file
> did. But installing from the tar file doesn't install Ipython in the
> site-packages directory. It installs it wherever you untar the tar
> file. I don't remember ever having to deal with this before. Most
> things just install in the site-packages directory without me having
> to do anything special.

You read the installation instructions and did a 'python setup.py
install' as it states, yes?

Installed that way for Python 2.7.2 under Win64 with no issues
whatsoever.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-19 Thread alex23
On Dec 19, 2:35 pm, Chris Angelico  wrote:
> Point to note:
>
> list,set = set,list  # Request a death sentence from the next maintainer
>
> is perfectly legal code. Now, what does your "args=" line do?
>
> ChrisA

Why are you directing this at my mocking of the OPs idea when the same
issue is present in his proposal?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie Question: Obtain element from list of tuples

2011-12-19 Thread alex23
On Dec 19, 4:46 pm, "Frank Millman"  wrote:
> Am I missing something?

No, I seem to be. I have _no_ idea how I got that original syntax to
work :|

My apologies, DevPlayer's suggestion is much more sensible, although
slices are still handy when dealing with groups of values.

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


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-19 Thread alex23
On Dec 20, 7:57 am, Andrew Berg  wrote:
> But what about the example he gave about being logged into a customer's
> machine with only ed available? I suppose such fools would not be worthy
> of your business.

Do you mean directly editing the source code on a production machine?
Because that's pretty much the only scenario I can come up with where
that's plausible.

If I was doing that, _I_ wouldn't be worth doing business with.

So you only have ssh & ed: at the very least you should be making
changes against your local copy, TESTING THEM, and then copy&paste
directly onto the remote box.

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


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-19 Thread alex23
Eelco  wrote:
> Having two seperate symbols seperated by whitespace, as in @list args
> strikes me as a terrible break of normal python lexical rules.

You mean like 'is not'? And the upcoming 'yield from'?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-19 Thread alex23
On Dec 19, 8:15 pm, Eelco  wrote:
> What does that have to do with collection packing/unpacking?

It's mocking your insistance that collection unpacking is a type
constraint.

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


Re: Newbie Question: Obtain element from list of tuples

2011-12-18 Thread alex23
Roy Smith  wrote:
> A common convention
> is that when you're unpacking a tuple (or a list, I suppose) and are
> only interested in some of the elements, you unpack the others into "_".
> Thus:
>
> _, _, _, _, pid, _, _, _ = recs[19]

Pre-namedtuple, I used to like using named slices for this:

cPID = slice(19)
pid = recs[cPID]

cHostPort = slice(99,100)
host, port = recs[cHostPort]

etc.

The suggestions of having your query return a dictionary where
possible are the most ideal, but if it's not possible you can always
wrap the result tuple in a namedtuple:

from collections import namedtuple

Staff = namedtuple('Staff',
['firstname','lastname','age','position'])

sql_result = ('John', 'Example', '30', 'Dummy')
staff_record = Staff(sql_result)

print staff_record.firstname, staff_record.age
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-18 Thread alex23
Evan Driscoll  wrote:
> My problem with it is that it in some sense is forcing me to make a
> decision I don't care about. Yes, what we have now is less flexible, but
> I have *never* said "man, I wish this *args parameter were a list
> instead of a tuple".

And if you _did_, then one of the first lines in your function would
be:

args = list(args)

Which is obvious to everyone, doesn't modify existing behaviour,
doesn't force everyone without a fetish for change to add unnecessary
cruft to their function signature...

Except, OMG, list() is RETURNING A LIST, which is an OBVIOUS type
constraint. I propose that:

args = @set list(args)

Will coerce args into a list and then give me a set in return.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: % is not an operator [was Re: Verbose and flexible args and kwargs syntax]

2011-12-15 Thread alex23
On Dec 16, 3:01 pm, Chris Angelico  wrote:
> And I would be most sorry to see % renamed to mod in Python.
>
> "Hello, %s! My favourite number is %d." mod ("Fred",42)   # This just
> looks wrong.

Finally we can give this operator a more fitting name - I propose
'inject' - and put an end to this insane desire to leverage off pre-
existing knowledge of other languages.

Furthermore, I suggest that no two languages should ever have
identical semantics, just to avoid potential confusion.

New concepts for all!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: % is not an operator [was Re: Verbose and flexible args and kwargs syntax]

2011-12-15 Thread alex23
Eelco  wrote:
> To tie it back in with python language design; all the more reason not
> to opt for pseudo-backwards compatibility. If python wants a remainder
> function, call it 'remainder'. Not 'rem', not 'mod', and certainly not
> '%'.

Good luck with the PEP.

> Its the more pythonic way; a self-describing name, rather than
> poorly defined or poorly understood cryptology.

"Although practicality beats purity."

I'm still utterly agog that anyone finds the operator % confusing.
-- 
http://mail.python.org/mailman/listinfo/python-list


PyCharm, .idea, and source control

2011-12-14 Thread alex23
Hey everyone,

I've been using PyCharm for the past month and only just hit an issue
that I'm hoping someone else may have some experience with resolving.
My problem has to do with PyCharm storing project configuration files
in its .idea folder inside the project.

This is both a mix of project-level settings and individual
customisations. The recommendation is to check this folder into the
repo as well  - excluding the files of individual settings - but I'm
the only developer here using PyCharm and polluting the project with
one user's settings would not be received well. More so, even if I
_did_ this, I'd still need to be storing my individual settings
elsewhere.

So what I'm currently doing is having git ignore the .idea folder, and
then subsequently turning the folder into its own repo and storing it
separately. Ideally I'd just like to be able to have all of the
project-config folders in one user-definable location, but I haven't
found any way to do that.

Has any one else hit this issue, and if so, any tips of resolving it
elegantly?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I love the decorator in Python!!!

2011-12-12 Thread alex23
On Dec 13, 2:27 am, Robert Kern  wrote:
> On 12/12/11 3:36 AM, alex23 wrote:
>
> > On Dec 9, 8:08 pm, Robert Kern  wrote:
> >> On 12/9/11 5:02 AM, alex23 wrote:
> >>> The 3rd party 'decorator' module takes care of issues like docstrings
> >>> &    function signatures. I'd really like to see some of that
> >>> functionality in the stdlib though.
>
> >> Much of it is:
>
> >>    http://docs.python.org/library/functools#functools.update_wrapper
>
> > Ah, cheers :) Is that a recent addition? The lack of note makes it
> > seem like it was there from the beginning?
>
> The module was added in Python 2.5 as noted at the top of the page.

I had thought you meant it now included function signature handling,
as that was the context at the time. No biggie.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread alex23
On Dec 13, 3:12 am, Eelco  wrote:
> But to relate it to the topic of this thread: no, the syntax does not
> allow one to select the type of the resulting sequence. It always
> constructs a list.

So by this argument, _every_ function that returns a list should take
an optional argument to specify an alternative form of sequence.

What, exactly, is so onerous about coercing your list to _whatever_
type you want? You know, like everybody else has been.

What does this _gain_ you other than one less line of code?


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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread alex23
On Dec 12, 10:21 pm, Eelco  wrote:
> >  Modulo is hardly an obscure operation. "What's the remainder...?" is a
> >  simple question that people learn about in primary school.
>
> So is 'how much wood would a woodchucker chuck if a woodchucker could
> chuck wood?'. But how often does that concept turn up in your code?

That comment right there? That's the moment every serious coder
stopped paying attention to a single word you say.

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


Re: Dynamic variable creation from string

2011-12-12 Thread alex23
On Dec 12, 10:49 pm, 8 Dihedral 
wrote:
> This is the way to write an assembler or
> to roll out a script language to be included in an app
> by users.

This is a garbage comment that has absolutely nothing to do with the
topic at hand _at all_.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: curses (or something) for windows

2011-12-12 Thread alex23
On Dec 13, 7:15 am, Eric  wrote:
> Is there something similar to curses available for the Windows version
> of Python (2.7, community edition)?  Preferably something built-in.
> In general, I'm looking to do gui-ish things from within the command
> window.
>
> Also, in particular, is there a way to get the console size (rows,
> cols).  I've seen how to do it in unix land but not for windows.
>
> TIA,
> eric

Check out http://www.lfd.uci.edu/~gohlke/pythonlibs/

It's a fantastic resource, Win32 & 64 versions of a lot of packages.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic variable creation from string

2011-12-12 Thread alex23
On Dec 8, 3:09 am, Massi  wrote:
> in my script I have a dictionary whose items are couples in the form
> (string, integer values), say
>
> D = {'a':1, 'b':2, 'c':3}
>
> This dictionary is passed to a function as a parameter, e.g. :
>
> def Sum(D) :
>     return D['a']+D['b']+D['c']
>
> Is there a way to create three variables dynamically inside Sum in
> order to re write the function like this?
>
> def Sum(D) :
>     # Here some magic to create a,b,c from D
>     return a+b+c

Okay, here's a possible solution that doesn't rely on exec, but does
use the third-party module byteplay (which I believe limits it to
Python 2.5-2.7) and tries to retain as much as possible your syntax
(with some slight adjustments):

from byteplay import Code, opmap

class VariableInjector(dict):
def transmute(self, opcode, arg):
if (opcode == opmap['LOAD_GLOBAL']) and (arg in self):
self._transmuted.append(arg)
return opmap['LOAD_FAST'], arg
return opcode, arg

def make_locals(self, args):
locals = []
for arg in args:
locals.append((opmap['LOAD_CONST'], self[arg]))
locals.append((opmap['STORE_FAST'], arg))
return locals

def bind_to(self, function):
function.ofunc_code = function.func_code
def _(*args, **kwargs):
self._transmuted = []
code = Code.from_code(function.ofunc_code)
code.code = [self.transmute(op, arg) for op, arg in
code.code]
code.code = self.make_locals(self._transmuted) +
code.code
function.func_code = code.to_code()
return function(*args, **kwargs)
return _

For your example, you'd use it like this:

>>> def sum():
... return a + b + c
...
>>> def product():
... return a * b * c
...
>>> data = VariableInjector(a=1,b=2,c=3)
>>> sum = data.bind_to(sum)
>>> product = data.bind_to(product)
>>> sum()
6
>>> product()
6
>>> data
{'a': 1, 'c': 3, 'b': 2}
>>> data['a'] = 100
>>> sum()
105
>>> product()
600

I'm not sure how rigorous this would be in real use but it's passed
the few quick toy cases I've tried it out on.

Any thanks should go to Michael Foord, as this borrows heavily from
his self-less metaclass example:
http://www.voidspace.org.uk/python/articles/metaclasses.shtml
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I love the decorator in Python!!!

2011-12-11 Thread alex23
On Dec 12, 2:51 pm, 8 Dihedral 
wrote:
> To wrap a function properly is different from the 1-line lampda.
>
> This is really functional programming.
>
> Every function can be decorated to change into a different one easily.
>
> There is  a method to replace every return action  of a python function
> into an  yield action without the source code.

How does this have _anything_ to do with my exchange with Robert?

If you're _not_ a markov chainer, you're trying way too hard to show
off what you know, and very little of it seems relevant to the thread.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tracking variable value changes

2011-12-11 Thread alex23
Andrea Crotti  wrote:
> Not sure if it's exactly pure python but Traits can actually do 
> thishttps://github.com/enthought/traits

At an attribute level, absolutely, but not at the variable level like
the OP is requesting.

It's a great package, though :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I love the decorator in Python!!!

2011-12-11 Thread alex23
On Dec 9, 8:08 pm, Robert Kern  wrote:
> On 12/9/11 5:02 AM, alex23 wrote:
> > The 3rd party 'decorator' module takes care of issues like docstrings
> > &  function signatures. I'd really like to see some of that
> > functionality in the stdlib though.
>
> Much of it is:
>
>    http://docs.python.org/library/functools#functools.update_wrapper

Ah, cheers :) Is that a recent addition? The lack of note makes it
seem like it was there from the beginning?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic variable creation from string

2011-12-11 Thread alex23
On Dec 11, 4:42 pm, Nobody  wrote:
> If just you're trying to avoid getting a repetitive strain injury in your
> right-hand little finger from typing all the [''], you could turn
> the keys into object attributes, e.g.:
>
>         class DictObject:
>             def __init__(self, d):
>                 for key, value in d.iteritems():
>                     setattr(self, key, value)
>         ...
>         o = DictObject(D)
>         # use o.a, o.b, etc

I hate this kind of laziness. I'd spend at least 5 minutes trying to
work out _why_ someone felt this was necessary and then get annoyed
that it was just to avoid typing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Outputting raw MIDI in realtime on Linux

2011-12-11 Thread alex23
On Dec 12, 12:14 pm, Nick Irvine  wrote:
> What do people use to output live MIDI on Linux, assuming it's
> possible?

Hey Nick,

I've yet to try this myself although it's long been on my to-do list.

There are a couple of packages on PyPI that emit MIDI:
http://pypi.python.org/pypi?%3Aaction=search&term=midi

There is also an older project that provides a basic midi step
sequencer. I can't find a proper package or installer, but you might
find something useful in the 'midi_functions.py' file here:
http://www.akjmusic.com/software/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I love the decorator in Python!!!

2011-12-08 Thread alex23
On Dec 9, 2:38 am, Chris Angelico  wrote:
> One piece of sophistication that I would rather like to see, but don't
> know how to do. Instead of *args,**kwargs, is it possible to somehow
> copy in the function's actual signature? I was testing this out in
> IDLE, and the fly help for the function no longer gave useful info
> about its argument list.

The 3rd party 'decorator' module takes care of issues like docstrings
& function signatures. I'd really like to see some of that
functionality in the stdlib though.

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


Re: Single key press

2011-12-06 Thread alex23
On Dec 6, 3:49 pm, Sergi Pasoev  wrote:
> I wonder if it is realistic to get a single key press in Python
> without ncurses or any similar library.

It's possible using Tkinter in the standard library:

http://www.daniweb.com/software-development/python/code/216830

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


Re: Questions about LISP and Python.

2011-12-05 Thread alex23
On Dec 6, 2:36 pm, Xah Lee  wrote:
> The python community is full of fanatics with their drivels.

You do know that you could just fuck right off and leave us to it,
yes?

In general, it's the person who is shrilly imposing their minority
opinion on a disinterested audience that deserves the title 'fanatic'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pragmatics of the standard is() function

2011-11-28 Thread alex23
On Nov 29, 5:22 am, Den  wrote:
> On Nov 26, 3:01 pm, Steven D'Aprano  > That is correct. You probably should rarely use `is`. Apart from testing
> > for None, use of `is` should be rare.
>
> With respect, I disagree with advice that the use of a language
> construct should be rare.  All constructs should be used
> *appropriately*.

Steven didn't say it _shouldn't_ be used, only that it it should be
_rarely_ used. General consensus would be that that is the most
appropriate use of 'is'.

Value comparisons are _far_ more common in Python than identity
comparisons, the ubiquitous None notwithstanding.

But for your general point, I totally agree. I feel the same way about
the ternary syntax, boolean defaults for conditionals etc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sick of distribute, setup, and all the rest...

2011-11-27 Thread alex23
rusi  wrote:
> While Ive never seen anything as ridiculous as the debian-rails in the
> python world, its still always a hobson choice:  use a deb package
> that will cleanly install, deinstall, upgrade etc but is out of date
> or use a fresh and shiny egg that messes up the system.

The only time I use the OS package manager to install a Python library
is if some other application requires it as a dependency.

If you're not making the distinction between your system install of
Python and your development install, you're really inviting a whole
world of pain and confusion on yourself.

With that approach in mind, I've never had any real issues using pip,
virtualenv etc for managing my development environment.

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


Re: Automatic import of submodules

2011-11-25 Thread alex23
On Nov 25, 11:00 pm, Massi  wrote:
> plugins
>     |
>     -- wav_plug
>           |
>           -- __init__.py
>           -- WavPlug.py
>     -- mp3_plug
>           |
>           -- __init__.py
>           -- Mp3Plug.py
> ...
>     -- etc_plug
>           |
>           -- __init__.py
>           -- EtcPlug.py

What do you gain by having each plugin as a package? Unless you're
storing other resources with each plugin, I'd move all your XXXPlug.py
files into plugins/ I'd also probably call the modules 'wavplug' and
the class 'WavPlug' to always make it clear  to which you're
referring.

> Every .py file contain a class definition whose name is identical to
> to the file name, so in my main script I have to import each submodule
> like that:
>
> from plugins.wav_plug.WavPlug import WavPlug
> from plugins.wav_plug.Mp3Plug import Mp3Plug
>
> and so on. This is uncomfortable, since when a new plugin is added I
> have to import it too. So my question is, is it possible to iterate
> through the 'plugins' directory tree in order to automatically import
> the submodules contained in each subdirectory?

It's not exactly automatic, but you could move all of those imports
into plugins/__init__.py, then just do a single

   from plugins import *

in your main module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python shell that saves history of typed in commands that will persist between reboots

2011-11-25 Thread alex23
On Nov 25, 6:58 pm, Tim Golden  wrote:
> Do you have the pyreadline module installed? ISTR that that takes
> over from the standard cmd processing...

I'm pretty sure I do.

It's really not an issue, though, as I tend to stick to linux &
iPython where possible :)

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


Re: python shell that saves history of typed in commands that will persist between reboots

2011-11-24 Thread alex23
Tim Golden  wrote:
> The interpreter inherits the command shell's history function:
> Open a cmd window and then a Python session. Do some stuff.
>
> Ctrl-Z to exit to the surrounding cmd window.
> Do some random cmd stuff: dir, cd, etc.
>
> Start a second Python session. up-arrow etc. will bring back
> the previous Python session's commands (and not the ones you
> entered in the surrounding shell)

This isn't true, at least not for ActivePython 2.7.2.5 under Windows
7-64. The second session has no history whatsoever.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python shell that saves history of typed in commands that will persist between reboots

2011-11-24 Thread alex23
On Nov 24, 6:51 pm, Tim Golden  wrote:
> The
> Ctrl-Z thing is what *exits* the interpreter on Windows (a la Ctrl-D
> on Linux).

With ActivePython, Ctrl-D works as well, which is a godsend as I'm
constantly working across Windows & linux.

> In short - on Windows, within one cmd shell you can open and exit
> the interpreter as many times as you like and the Python command
> history will be retained via the cmd shell's history mechanism,
> and kept distinct from the history of other things you may type
> into the cmd shell.

And again, I'm definitely not seeing this. Inside the one cmd shell,
each instance of Python has no recollection of the history of the last.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: suitability of python

2011-11-24 Thread alex23
Terry Reedy  wrote:
> This lead to Numerical Python, now Numpy, SciPy, and later Sage and
> other scientific and Python packages. I believe SciPy has an f2py
> (fortran to py) module to help with running Fortran under Python (but it
> has been years since I read the details).

Andrew Dalke recently did some work on f2pypy, as a step toward
running Fortran under PyPy:

http://www.dalkescientific.com/writings/diary/archive/2011/11/09/f2pypy.html

If PyPy's Numpy support was more advanced, I'd probably recommend the
OP start there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Interesting problem about uuid1

2011-11-21 Thread alex23
On Nov 21, 5:33 pm, sword  wrote:
> My colleague asks me an interesting problem about uuid library in
> python. In multicore system with multiprocessing, is it possible to
> get the duplicated uuid with uuid1?
>
> I just check the RFC 4122, and I can't find anything about multicore
> environment. Python's uuid1 method generates the uuid with time stamp,
> mac address, and algorithm to gen random numbers. So, I think it's
> possible to get the duplicate uuid1 at the same time.
>
> What about you? Hope for your reply

Check the library documentation: http://docs.python.org/library/uuid.html

uuid.uuid1([node[, clock_seq]])
Generate a UUID from a host ID, sequence number, and the current time.
If node is not given, getnode() is used to obtain the hardware
address. If clock_seq is given, it is used as the sequence number;
otherwise a random 14-bit sequence number is chosen.

Each process would have to not only execute at the exact same time, it
would have to generate the same 14-bit random sequence. And if you're
really concerned, try specifying a different clock_seq for each core.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What I do and do not know about installing Python on Win 7 with regard to IDLE.

2011-11-21 Thread alex23
"W. eWatson"  wrote:
> Comments?

Please don't start multiple threads on the same issue.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlalchemy beginner

2011-11-21 Thread alex23
On Nov 22, 10:25 am, Roy Smith  wrote:
> Everytime I've worked with SQLAlchemy, I've run away screaming in the
> other direction.  Sure, portability is a good thing, but at what cost?

I've never found SQLAlchemy to be anything but sane and approachable.
It's really worth understanding _how_ it works so you can see there's
no magic happening there.

What cost do you see inherit in the use of SQLAlchemy?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Both Python 2.5.2 and 2.7.2 flop the same way under Win 7

2011-11-20 Thread alex23
On Nov 19, 8:31 am, Stephen Hansen  wrote:
> Yes, its moderately annoying that you have to do this yourself; maybe
> you wouldn't if you installed 64-bit python, but I can't be sure. Maybe
> it has nothing to do with 32 or 64-bitness at all and my guess is wrong.

I've got the 32 bit version of 2.7 & the 64 bit of 3.2 installed under
Windows 7. I'm not seeing 'Edit with IDLE' options, instead I get
'Edit with Pythonwin' from the 32bit installation.

I'm also using ActivePython, though. I can honestly say I've never had
an issue under Windows with it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Both Python 2.5.2 and 2.7.2 flop the same way under Win 7

2011-11-20 Thread alex23
On Nov 19, 3:59 am, "W. eWatson"  wrote:
> Yes. I tried running it. Got nowhere.

Did you run it from the shell? Did it spit out any errors?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there any way to unimport a library

2011-11-20 Thread alex23
On Nov 21, 1:15 am, Gelonida N  wrote:
> I wondered whether there is any way to un-import a library, such, that
> it's occupied  memory and the related shared libraries are released.
>
> My usecase is following:
>
> success = False
> try:
>     import lib1_version1 as lib1
>     import lib2_version1 as lib2
>     success = True
> except ImportError:
>     pass
> if not success:
>     try:
>         import lib1_version2 as lib1
>         import lib2_version2 as lib2
>         success = True
>     except importError:
>         pass
> if not success:
>     . . .
>
> Basically if I am not amble to import lib1_version1 AND lib2_version1,
> then I wanted to make sure, that lib1_version1 does not waste any memory

A simple way would be to create packages for each version that import
the two dependencies:

  /version1/__init__.py:
import lib1_version1 as lib1
import lib2_version2 as lib2

  /version2/__init__.py:
import lib1_version2 as lib1
import lib2_version2 as lib2

Then create a single module to handle the importing:

  /libraries.py:

  __all__ = ['lib1', 'lib2', 'version']

  version = None
  _import_errs = []

  try:
from version1 import lib1, lib2
version = 1
  except ImportError as (err,):
_import_errs.append(err)

  if version is None:
try:
  from version2 import lib1, lib2
  version = 2
except ImportError as (err,):
  _import_errs.append(err)

  if version is None:
_format_errs = (('v%d: %s' % (ver, err)) for ver, err in
enumerate(_import_errs, 1))
raise ImportError('Unable to import libraries: %s' %
list(_format_errs))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Server Questions (2 of them)

2011-11-20 Thread alex23
On Nov 21, 10:27 am, Christian Heimes  wrote:
> It's possible to sandbox Python code, see
> http://docs.python.org/library/rexec.html

Although this has been deprecated since 2.6 & removed from 3.x (and
cautioned against for as long as I've used Python).

PyPy provides some sandboxing functionality that might be useful here:
http://codespeak.net/pypy/dist/pypy/doc/sandbox.html


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


Re: Both Python 2.5.2 and 2.7.2 flop the same way under Win 7

2011-11-17 Thread alex23
On Nov 18, 2:21 pm, "W. eWatson"  wrote:
> Because some  people think that's a solution, and ask. It's not. It
> leads to an error message.

No, people are saying "manually add IDLE _the correct way that Windows
can recognise_", not recommending you stuff random .pyw files into the
context menu and hope they work.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What exactly is "pass"? What should it be?

2011-11-17 Thread alex23
On Nov 18, 12:59 pm, Chris Angelico  wrote:
> If you call your dummy function something else, it may help
> readability/self-documentation too.

Or replace the pass with a docstring for the same effect:

  def silent(*args):
"""Null Object to repress reporting"""

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


Re: How to insert my own module in front of site eggs?

2011-11-17 Thread alex23
On Nov 18, 11:36 am, Roy Smith  wrote:
> What if the first import of a module is happening inside some code you
> don't have access to?

No import will happen until you import something. As long as you
change sys.path before you do, all subsequent imports will use that
path.

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


Re: Both Python 2.5.2 and 2.7.2 flop the same way under Win 7

2011-11-17 Thread alex23
On Nov 18, 2:55 am, "W. eWatson"  wrote:
> Comments?

Are you using the vanilla installer or ActiveState's ActivePython? I
find the latter integrates better with Windows.

Also, out of curiousity, 32 or 64 bit Windows?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use and usefulness of the as syntax

2011-11-17 Thread alex23
On Nov 18, 1:48 am, candide  wrote:
> # a.py
> import math as _math
>
> # b.py
> from a import *
>
> print _math.sin(0)       # raise a NameError
> print math.sin(0)        # raise a NameError
>
> so the as syntax is also seful for hiding name, isn'it ?

Not exactly. It's the * import mechanism here that's ignoring any
bindings that begin with an underscore. If you had:

   _dummy = 1

...inside of a.py, it wouldn't be pulled in either. As you state
later, 'as' is purely a binding convenience.

Incidentally, you can still allow * import to bring in underscore-
prefixed bindings by adding them to an __all__:

__all__ = ['_dummy']
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: staticmethod makes my brain hurt

2011-11-17 Thread alex23
On Nov 17, 1:24 pm, Ethan Furman  wrote:
> If you do need to sometimes call it from a method then still leave off
> the '@staticmethod', and give 'self' a default of 'None':
>
>      def _get_next_id(self=None):
>        [blah, blah, blah]
>        return id
>
>      user_id = IntField(required=True, default=_get_next_id)

And if the OP needs it to be a staticmethod as well, he can just wrap
the nested function:

  gen_next_id = staticmethod(_gen_next_id)

I think I like this approach best. I'm annoyed that I forgot functions
declared in a class scope were callable within the definition :)

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


Re: python shell that saves history of typed in commands that will persist between reboots

2011-11-16 Thread alex23
On Nov 17, 7:09 am, Ben Finney  wrote:
> You can then use that functionality in your Python interactive startup
> file. Here's mine:

Awesome, thank you for this. I use iPython where ever possible but
there are times where I just can't avoid the default shell and this
will help immensely.

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


Re: staticmethod makes my brain hurt

2011-11-16 Thread alex23
On Nov 17, 12:30 pm, Roy Smith  wrote:
> class C:
>     @staticmethod
>     def foo():
>         pass
>
>     print "inside", foo, callable(foo)
>
> print "outside", C.foo, callable(C.foo)
>
> I don't understand.  Why is foo not callable inside of the class
> definition?

Consider this:

>>> def foo(): pass
...
>>> foo = staticmethod(foo)
>>> callable(foo)
False

A staticmethod by itself does not appear to be callable.

Your internal 'foo' is referring to the staticmethod wrapper. Your
external 'C.foo' refers to the result returned by the class
mechanism's __getattr__, which I'm guessing is munged into a callable
at that point.

Where this comes up is that I'm trying to use a callable
> default in mongoengine:
>
> class User(Document):
>     @staticmethod
>     def _get_next_id():
>       [blah, blah, blah]
>       return id
>
>     user_id = IntField(required=True, default=_get_next_id)

What you're effectively trying to do is use a class before it has been
constructed to help construct itself.

Just define it as a helper function before the class declaration.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multilevel dicts/arrays v. tuples as keys?

2011-11-14 Thread alex23
Peter Otten <__pete...@web.de> wrote:
> If you need lookup only I'd prefer tuples, but sometimes you may want to
> retrieve all values with a certain k1 and
>
> d[k1]
>
> is certainly more efficient than
>
> [(k2, v) for (k1, k2), v in d.items() if k1 == wanted]

This was the hidden cost of the tuple/reverse-dictionary solution I
offered. The solution will of course depend on what the OP requires to
be more efficient: looking up keys from values, or working with
subsets of the data.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get keys from a dicionary

2011-11-13 Thread alex23
On Nov 11, 11:31 pm, macm  wrote:
>
> I pass a nested dictionary to a function.
>
> def Dicty( dict[k1][k2] ):
> print k1
> print k2
>
> There is a fast way (trick) to get k1 and k2 as string.

It might be possible to do something using a reverse dictionary and
getting rid of the nested dictionary.

This is a quick and simple 'two-way' dictionary class that works by
maintaining two dictionaries: the original key/value, and the reversed
value/key. It returns a list of keys, allowing for a value to be
assigned against more than

from collections import defaultdict

class TwoWayDict(dict):
def __init__(self, *args, **kwargs):
self._reversed = defaultdict(list)
for key, val in kwargs.iteritems():
self[key] = val

def __setitem__(self, key, value):
super(TwoWayDict, self).__setitem__(key, value)
self._reversed[value].append(key)

def getkeys(self, match):
return self._reversed[match]

>>> original = TwoWayDict(a=100,b='foo',c=int,d='foo')
>>> original.getkeys(100)
['a']
>>> original.getkeys('foo')
['b', 'd']

As for the nested dictionary, you could replace it with a _single_
dictionary that uses a composite key:

>>> original = TwoWayDict(a=100,b=100)
>>> original.getkeys(100)
['a', 'b']
>>> original = TwoWayDict()
>>> original['record1','user1'] = 'martin'
>>> original['record1','user2'] = 'robert'
>>> original['record2','user1'] = 'robert'
>>> original.getkeys('robert')
[('record1', 'user2'), ('record2', 'user1')]

> Whithout loop all dict. Just it!

The TwoWayDict class removes the need to loop across the dict looking
for keys that match a value by replacing it with another dict lookup.
Reducing the nested dict to a single dict with composite keys removes
the need to traverse the outer dict to compare against its children.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get keys from a dicionary

2011-11-13 Thread alex23
On Nov 11, 11:31 pm, macm  wrote:
>
> I pass a nested dictionary to a function.
>
> def Dicty( dict[k1][k2] ):
> print k1
> print k2
>
> There is a fast way (trick) to get k1 and k2 as string.

It might be possible to do something using a reverse dictionary and
getting rid of the nested dictionary.

This is a quick and simple 'two-way' dictionary class that works by
maintaining two dictionaries: the original key/value, and the reversed
value/key. It returns a list of keys, allowing for a value to be
assigned against more than

from collections import defaultdict

class TwoWayDict(dict):
def __init__(self, *args, **kwargs):
self._reversed = defaultdict(list)
for key, val in kwargs.iteritems():
self[key] = val

def __setitem__(self, key, value):
super(TwoWayDict, self).__setitem__(key, value)
self._reversed[value].append(key)

def getkeys(self, match):
return self._reversed[match]

>>> original = TwoWayDict(a=100,b='foo',c=int,d='foo')
>>> original.getkeys(100)
['a']
>>> original.getkeys('foo')
['b', 'd']

As for the nested dictionary, you could replace it with a _single_
dictionary that uses a composite key:

>>> original = TwoWayDict(a=100,b=100)
>>> original.getkeys(100)
['a', 'b']
>>> original = TwoWayDict()
>>> original['record1','user1'] = 'martin'
>>> original['record1','user2'] = 'robert'
>>> original['record2','user1'] = 'robert'
>>> original.getkeys('robert')
[('record1', 'user2'), ('record2', 'user1')]

> Whithout loop all dict. Just it!

The TwoWayDict class removes the need to loop across the dict looking
for keys that match a value by replacing it with another dict lookup.
Reducing the nested dict to a single dict with composite keys removes
the need to traverse the outer dict to compare against its children.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: all() is slow?

2011-11-13 Thread alex23
On Nov 13, 4:28 pm, Devin Jeanpierre  wrote:
> > which implies that getattr(x, 'a!b') should be equivalent to x.a!b
>
> No, it does not. The documentation states equivalence for two
> particular values

It states equivalence for two values _based on the name_.

"If the string is the name of one of the object’s attributes, the
result is the value of that attribute. For example, getattr(x,
'foobar') is equivalent to x.foobar."

The string 'a!b' is the name of the attribute, ergo getattr(x, 'a!b')
_is_ x.a!b. If x.a!b isn't valid CPython, then etc.

> CPython breaks that equivalence

So you're outright ignoring the comments that this behaviour is to
make CPython more performant?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: property decorator and inheritance

2011-11-10 Thread alex23
On Nov 11, 2:03 pm, Laurent  wrote:
> Hi. I couldn't find a way to overwrite a property declared using a decorator 
> in a parent class.

> class Polite:
>     @property
>     def greeting2(self, suffix=", my dear."):
>         return self._greeting + suffix

Here you set up greeting2 as a property.

> class Rude(Polite):
>     @property
>     def greeting2(self):
>         return super().greeting2(suffix=", stupid.")

Here you call Polite.greeting2 as a function.

> print("r.greeting2 =", r.greeting2) # TypeError: 'str' object is not callable

And here it's telling you that you're trying to treat a string - the
output of Polite.greeting2 - as a function.

The problem isn't that you cannot override greeting2 on Rude, it's
that you can't treat properties as functions, so you can't pass in a
new suffix. Instead, break the suffix out as a class attribute, then
each descendent just needs to override that attribute:

  class Polite(object):
suffix = ', my dear'

@property
def greeting(self):
  return 'Hello' + self.suffix

  class Rude(Polite):
suffix = ', stupid'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: all() is slow?

2011-11-09 Thread alex23
On Nov 10, 11:26 am, Devin Jeanpierre  wrote:
> I don't really know anything about him or why people respect him, so I
> have no reason to share your faith.

But you're happy to accept the opinions of random posters saying "exec
is evil"? (And it's really not a good idea to be proud of your
ignorance...)

> Like, why can't "--" be a name?

Why would you ever want it to be?

> I don't like the use of exec, and I don't like the justification (it
> seems handwavy).

As opposed to your in-depth critique?

> I pointed this out in a thread full of people saying
> "never EVER use exec this way", so it's obviously not just me that
> thinks this is awful.

No, instead you have a thread full of people happy to criticise
something for which they're providing no alternative implementation.
You can't exactly say _why_ it's bad, other than other people have
echoed it, but you won't actually do anything about it.

> I think somebody will read it and think this is a good idea.

Just as I thought.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: all() is slow?

2011-11-09 Thread alex23
On Nov 10, 8:16 am, John Nagle  wrote:
>      CPython is slow. It's a naive interpreter.  There's
> almost no optimization during compilation.  Try PyPy
> or Shed Skin.

Sometimes people need to understand the performance characteristics of
CPython because it's what they have to use. Pointing them at
alternative implementations isn't an answer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: understand program used to create file

2011-11-01 Thread alex23
On Nov 2, 5:27 am, pacopyc  wrote:
> Hi, I have about 1 files .doc and I want know the program used to
> create them: writer? word? abiword? else? I'd like develop a script
> python to do this. Is there a module to do it? Can you help me?

Word documents store metadata inside of them, one field of which is
the program used to create them. This shows you how to use pywin32 to
access them:

http://www.galalaly.me/index.php/2011/09/use-python-to-parse-microsoft-word-documents-using-pywin32-library/

This won't be a foolproof solution, unfortunately. A random
examination of doc files shows that not all of them have the required
field set.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __dict__ attribute for built-in types

2011-10-27 Thread alex23
On Oct 28, 8:52 am, candide  wrote:
> No but I'm expecting from Python documentation to mention the laws of
> Python ...

It's not a "law", it's an _implementation detail_. The docs don't tend
to mention every such decision made because that's what the source is
for.

> But beside this, how to recognise classes whose object doesn't have a
> __dict__ attribute ?

The better question is: why do you need to be able to?

> Is it possible in the CPython implementation to write something like this :
> "foo".bar = 42
> without raising an attribute error ?

Why are you trying to modify an immutible object?

If you really want to assign attributes to string objects, subclass
str.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: webapp development in pure python

2011-10-25 Thread alex23
Laszlo Nagy  wrote:
> My Python module would connect to a database server and query
> some data, then display it in a grid. This cannot be compiled into
> javascript because of the database server connection.

So what you want is for everything to happen server-side, with html
output sent to the client?

Perhaps you could build on top of ToscaWidgets. They encapsulate HTML
& JS, so you'll still need to work with them for custom widgets.

> With pyjamas, I
> would have to create the server side part separately, the user interface
> separately, and hand-code the communication between the widets and the
> server side.

That's pretty much true of all non-trivial web development, though.

There's a lot to be said for sucking it up and embracing traditional
methods rather than flying against common wisdom and cobbling together
something that works against web technologies rather than with them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: revive a generator

2011-10-24 Thread alex23
On Oct 21, 12:09 pm, Yingjie Lan  wrote:
> Secondly, it would be nice to automatically revive it.

Sure, it's always nice when your expectation of a language feature
exactly matches with its capabilities.

When it doesn't, you suck it up and code around it.

Because at the very least it's a hell of a lot quicker than waiting
for the language to change for you.


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


Re: revive a generator

2011-10-24 Thread alex23
On Oct 21, 11:46 am, Yingjie Lan  wrote:
> I am still not sure why should we enforce that 
> a generator can not be reused after an explicit 
> request to revive it?

No one is "enforcing" anything, you're simply resisting implementing
this yourself. Consider the following generator:

  import random
  def randgen():
for _ in xrange(10):
  yield random.choice(['Hi','Lo'])

  >>> [x for x in randgen()]
  ['Hi', 'Hi', 'Lo', 'Hi', 'Lo', 'Lo', 'Lo', 'Lo', 'Hi', 'Hi']

What would you expect when you reset that generator? A newly
randomised set of values, or the _same_ set of values?

What if the generator is reading from an external source, like
temperature values? Once revived, should it return the exact same
sequence it originally did, or should it retrieve new values?

Now, no matter which decision you made, why is your expectation of
behaviour the right one? Why should the generator protocol support
your convience in particular?

If you need your generator to be re-usable, make a factory that
creates it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating very similar functions with different parameters

2011-10-24 Thread alex23
Guido wrote an article on a quick and easy multimethod implementation
using a decorator:
http://www.artima.com/weblogs/viewpost.jsp?thread=101605
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compare range objects

2011-10-20 Thread alex23
On Oct 21, 12:16 pm, Chris Angelico  wrote:
> Hmm. I wonder would slice objects be appropriate?
> They're not iterable though

They're not hashable either, which kind of surprised me.

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


Re: strange comparison result with 'is'

2011-10-18 Thread alex23
On Oct 18, 3:53 am, Terry Reedy  wrote:
> This has come up enough that I opened http://bugs.python.org/issue13203

I really don't get the new Python user obsession with id(). I don't
think I've ever used it, in production code or otherwise.

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


Re: Benefit and belief

2011-10-18 Thread alex23
On Oct 18, 6:52 am, Ben Finney  wrote:
> A belief that doesn't match reality is a delusion. That doesn't change
> when someone thinks it's an epiphany: it's still a delusion.

Apparently there was some talk about removing delusional as a
classification from the DSM due to its definition being, in part, that
it was an _unshared_ belief (which seems to be a loophole for not
locking up the religious). With the advent of the internet, it's
almost impossible to _not_ find someone who agrees with you, no matter
how batshit crazy you might be :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Benefit and belief

2011-10-18 Thread alex23
DevPlayer  wrote:
> Ever hear/read the term: "It's all good."? A reference to Karma and
> how things will work out for the better in the end inspite of what you
> see now... A great example of "Everything is Symantics".

"Semantics". Also: nonsense. You're conflating an ethical system with
a _completely_ indepdent symbolic one via overloaded terminology.
That's pretty true of most of your rants, actually.

> And another weird notion to put forward. "2" as a numberic quantity by
> itself is utterly meaningless. Two what?

More nonsense. The whole field of number theory would like to dispute
this point. So would Python: i = 2. What exactly does i hold? Two
integers?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: type vs. module (part2)

2011-10-17 Thread alex23
On Oct 17, 9:11 am, Shane  wrote:
> I now have two questions: How does Python allow two classes of the
> same
> type as evidenced by identical ``print type()' output and
> different id
> outputs?

You are looking at the id of two _instances_ of the class, not of the
class itself.

>>> class Example(object):
...   pass
...
>>> e1, e2 = Example(), Example()
>>> type(e1), type(e2)
(, )
>>> id(type(e1)), id(type(e2))
(20882000, 20882000)
>>> id(e1), id(e2)
(25931760, 25968816)

> Also, which module is t,t1 actually in? Is it "a.b.f"? Or is it
> "a.b.t.d".

Which module did you declare them in? What makes you think they're
defined somewhere other than what .__module__ is telling you?

My guess is your class is in a.b.f, your instances are created in
a.b.t.d, and you've demonstrated very powerfully the value of
meaningful names in code.

> I am totally confused.

And you have the source code. Imagine how we feel.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python library for generating SQL queries [selects, alters, inserts and commits]

2011-10-14 Thread alex23
Tim Chase  wrote:
> I'm not sure it can entirely be chalked up to not looking hard
> enough.

It's explicitly cited in the feature list:

Raw SQL statement mapping
SQLA's object relational query facilities can accommodate raw SQL
statements as well as plain result sets, and object instances can
be generated from these results in the same manner as any other
ORM operation. Any hyper-optimized query that you or your DBA can
cook up, you can run in SQLAlchemy

http://www.sqlalchemy.org/features.html

That it's expression language translates down to pure SQL is also
shown within the first few sections of the tutorial too:

http://www.sqlalchemy.org/docs/core/tutorial.html

I'm not sure how they could make it more obvious.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-14 Thread alex23
On Oct 15, 12:32 pm, alex23  wrote:
> from functools import partial

You can ignore this, sorry, leftover from earlier code :)


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


Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-14 Thread alex23
On Oct 13, 10:35 pm, "Martin P. Hellwig" 
wrote:
> def do_something():
>      a = 4
>      b = 2
>      c = 1
>      ooo:
>          a += 1
>          b += 2
>          c += 3
>      print(a, b, c)
>
> What I would expect to happen that all statements within the ooo block
> may be executed out
> of order. The block itself waits till all statements are returned before
> continuing.
>
> What do you think?

You can do this right now with Python 3.2+ and concurrent.futures:

from concurrent.futures import ThreadPoolExecutor
from functools import partial
import time

class DoSomething:
a = 4
b = 2
c = 1

def add(self, prop, val):
cur = getattr(self, prop)
time.sleep(cur)
print('Adding %d to %s' % (val, prop))
setattr(self, prop, cur + val)

def __init__(self):
with ThreadPoolExecutor(max_workers=3) as pool:
pool.submit(self.add, 'a', 1)
pool.submit(self.add, 'b', 2)
pool.submit(self.add, 'c', 3)
print(self.a, self.b, self.c)

DoSomething()

Here we call 'ooo' the ThreadPoolExecutor context manager :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-14 Thread alex23
On Oct 14, 4:56 pm, Carl Banks  wrote:
> But you can see that, fully realized, syntax like that can do much more
> than can be done with library code.

Well sure, but imaginary syntax can do _anything_. That doesn't mean
it's possible within CPython.

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


Re: Opportunity missed by Python ?

2011-10-14 Thread alex23
On Oct 13, 8:07 pm, Chris Angelico  wrote:
> Python, as I found out to my detriment, is practically impossible to
> sandbox effectively.

The latest version of PyPy introduces a prototype sandbox:

http://pypy.org/features.html#sandboxing

It'll be interesting to see how effective this is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python library for generating SQL queries [selects, alters, inserts and commits]

2011-10-11 Thread alex23
On Oct 12, 1:14 am, Alec Taylor  wrote:
> They look good, but I'm looking for something which can "compile" down
> to normal SQL code.

Then you're not looking hard enough. SQLAlchemy does this.

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


Re: A tuple in order to pass returned values ?

2011-10-09 Thread alex23
Jean-Michel Pichavant  wrote:
> However, I'm not sure it fixes the main issue: unpacking. Unpacking
> prevents you from adding any additional fields to your 'tuple' without
> breaking any line of code that was unpacking the tuple (to oppose to
> accessing an object attribute).

Generally, if it's a small, known, unlikely-to-change structure, I'd
use a tuple. For anything else I'd use a class, namedtuple or bunch.

However, pre-namedtuples I'd usually abstract away the field
referencing with indices and lambdas:

   name = 0
   role = 1
   name_role = lambda t: (t[name], t[role])

   name, role = name_role(record)

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


Re: Is it possible to create C-style "main" function in Python? (for teaching purposes)

2011-10-06 Thread alex23
Dennis Lee Bieber  wrote:
>         While I wouldn't want to write an FFT in COBOL, one can't deny that
> laying out fixed width reports and moving blocks of decimal data between
> record layouts is quite easy in COBOL.

Well, sure, but there's still plenty of pain in the verbosity :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convenient filtering in for cycles

2011-10-05 Thread alex23
On Oct 6, 2:55 am, Stefano Maggiolo  wrote:
> I would like to know if there is a (more) convenient way of doing this
> structure:
>
> ===(1)===
> for x in l:
>     if P(x):
>         do_stuff(x)
> ==

map(do_stuff, filter(P, l))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to create C-style "main" function in Python? (for teaching purposes)

2011-10-05 Thread alex23
Ben Finney  wrote:
> This mocking is hurtful to people who identify too strongly with COBOL.
> I wonder whether that means it's intentionally hurtful.

Far, _far_ less hurtful than COBOL itself...

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


Re: Is it possible to create C-style "main" function in Python? (for teaching purposes)

2011-10-05 Thread alex23
On Oct 5, 11:10 pm, Chris Angelico  wrote:
> The absence from the language doesn't prove that. All it means is
> that, on those rare occasions when a goto would have been correct, the
> programmer had to make do with something else :-)

Like the goto module? :)

http://entrian.com/goto/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to create C-style "main" function in Python? (for teaching purposes)

2011-10-04 Thread alex23
Steven D'Aprano  wrote:
> Imported modules are variables like any other, and as they usually exist
> in the global scope, so they will all need to be explicitly referenced as
> global. This will get tiresome very quickly, and is a cure far worse than
> the disease, and alone is enough to disqualify this suggestion from
> serious consideration.

But on the gripping hand, it is a clear triumph of "Explicit is better
than implicit." ;)

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


Re: how to call java methods in python

2011-10-03 Thread alex23
On Oct 4, 4:39 pm, masood shaik  wrote:
> Please help me.

Please help us help you. You've given us nothing but an error message.
(Which seems to indicate that you're trying 'import Calculator'...)

What are you using to call Java methods in Python?

Can you provide a small example of code that demonstrates the problem?

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


Re: Chaos Theory [was Re: Benefit and belief]

2011-10-03 Thread alex23
Zero Piraeus  wrote:
> A dissenting view [and a Kill Bill spoiler, of sorts]:
>
> http://www.youtube.com/watch?v=PdWF7kd1tNo

A fun diatribe, sure, but still an outsider view that is in direct
conflict with how the characters are actually portrayed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Chaos Theory [was Re: Benefit and belief]

2011-10-03 Thread alex23
rantingrick  wrote:
> TrueWiseObserver: Wrong pseudo. Superman will ALWAYS be superman even
> if he wears a dress and stilettos. Clark Kent is just an assumed
> identity of Superman.

Actually, he identifies with Clark Kent, Superman is the secret
identity.

You're thinking of Batman, for whom Bruce Wayne is the mask.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to create C-style "main" function in Python? (for teaching purposes)

2011-10-03 Thread alex23
Sorry for hijacking Alec's response but I didn't see the OP.

> Aivar Annamaa  wrote:
> > I'm looking for a trick or hidden feature to make Python 3 automatically
> > call a "main" function but without programmers writing `if __name__ ==
> > "__main__": ...`

One direct way is to call it from the command line:

   python -c "import mymodule; mymodule.main()"

After your students have had to use that verbose form for a while,
they'll be more than happy to add the boilerplate themselves to the
end of their modules :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to create C-style "main" function in Python? (for teaching purposes)

2011-10-03 Thread alex23
rantingrick  wrote:
> Why? Well because many times i find myself wondering if this or that
> variable is local or global -- and when i say "global" i am speaking
> of module scope! The "global" cures the ill.

Given your stated propensity for huge code blocks not chunked into
functions, I'm not surprised you lose track of what is global, what is
nonlocal etc. This is another clear advantage of small functions: you
can view it all at once. For the rest of us, a variable is global if
its referenced but not defined in a specific scope. There's no need
for such verbose hand-holding.

I'd say the wart is in your design practice rather than the language
itself.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-30 Thread alex23
> > On Sep 29, 10:23 pm, rantingrick  wrote:
> > > What is so bad about breaking code in obscure places?

> On Sep 29, 9:50 pm, alex23  wrote:
> > Try coding in PHP across minor release versions and see how you feel
> > about deprecating core functions on a whim.

On Sep 30, 11:54 pm, rantingrick  wrote:
> I never said we should remove it now, i said we should deprecate it
> now.

Actually, *I* said deprecate, *you* said break. I don't see the word
'remove' anywhere in my comment.

> Please Google deprecate.

Please read what I wrote rather than what you want me to have said.

> Well "alex" i can't see a mob approaching with pitchforks because we
> deprecate a misplaced and rarely used functionality of the stdlib.

No, but you don't see a lot of things. You're genuinely convinced that
your viewpoint is superior and singularly correct. I don't think
you're a reasonable arbiter of what functionality should be added or
removed from the stdlib.

> Well "alex", like yourself, i hold expertise in many fields BESIDES
> programming. One of which being psychology.

That only makes the claims that you regularly post about others even
more offensive.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Motion Tracking with Python

2011-09-29 Thread alex23
On Sep 30, 3:31 pm, Chris Angelico  wrote:
> Unless someone's seriously considering porting the Linux
> kernel to Python...

Well, they've certainly asked:
http://bytes.com/topic/python/answers/37048-reimplenting-linux-kernel-python

And while not Linux kernels, there are two projects attempting to
develop Python-implemented OSes:
http://code.google.com/p/cleese/
http://unununium.org

> or writing a device driver in Python...

http://www.stealth-x.com/programming/driver-writing-with-python.php

> or writing a MS Word virus in Python...

Now that's just crazy talk.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Motion Tracking with Python

2011-09-29 Thread alex23
On Sep 30, 12:16 pm, Derek Simkowiak  wrote:
> It's especially neat because my daughter and I worked together on this
> project. We used it to track her two pet gerbils, as part of her science
> fair project. She wrote her own (separate) Python script to read the
> motion tracking log files, compute distance and velocity, and then
> export those values in a CSV file.

Thank you for sharing this. My daughter is only 20 months at the
moment but I definitely hope to teach her coding as she gets older.

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


Re: Hermeneutics and computer science [was off-topic, now back on]

2011-09-29 Thread alex23
On Sep 30, 2:34 pm, Steven D'Aprano  wrote:
> alex23 wrote:
> > I'm slowly seeing more and more interest in applying
> > a discipline that arose out of the
> > study of religious texts.
>
> Tell us more, please.

Well, it's mostly from real world discussions and may actually be an
artefact of my holding degrees in both philosophy & computer
science :)  But googling "hermeneutics computer science" does bring up
a heap of entries, although the highest ranked is from 1979, so I may
have oversold the idea of it being a growing interest.

Amazon also shows that there have been a number of publications
dealing with this:
http://www.amazon.com/s?ie=UTF8&keywords=Hermeneutics.&rh=n%3A3508%2Ck%3AHermeneutics.

For me, the main aspect of hermeneutics that could apply here - to
programming especially - is the concept that reading a text informs
you for subsequently reinterpreting the text (the "hermeneutic circle"
of Heidegger). No philosophical notion of truth is needed to explain
this, I see much in common with iterative development processes.
Multiplicity of perspective is similarly important in interpretation:
again, computer systems are developed with many user roles and thus
many 'views' of what is happening.

In the interest of fair play, if anyone still smarting at my flippancy
wants to take a swing at my belief system, it's mostly cobbled
together from Nietzsche, Wittgenstein & Crowley. Personal email
preferably, let's keep it off the list unless its particularly witty :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-29 Thread alex23
On Sep 30, 3:14 pm, Ben Finney  wrote:
> alex23  writes:
> > On Sep 29, 10:23 pm, rantingrick  wrote:
> > > GvR should be texting me every night in hopes that some of my API
> > > genius will rub off on him.
>
> > Are you off your medication again?
>
> Please don't make personal attacks. If you don't feel like addressing
> the content of his message, don't switch to implying he has a mental
> illness.

Fair enough. It was intended more as a ludicrous accusation to his
ridiculous claim. Lord knows there's enough in his posts to focus on
without the ad hominems :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Benefit and belief [was Re: Suggested coding style]

2011-09-29 Thread alex23
Dennis Lee Bieber  wrote:
>         Well... We could try for equality in offense -- the Torah or the
> Koran? Maybe the Tripitaka or Sutras?

I always enjoyed the possibly apocryphal claim that the design of VRML
was influenced by the story of Indra's Net. Maybe some religious tomes
are just better? :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Off-Topic Posts and Threads on the Python Mailing List

2011-09-29 Thread alex23
Chris Angelico  wrote:
> We may happen to have coincidental interest in (say)
> music, but just because some group of us (or even all of us) all enjoy
> music does not mean that it'd be on-topic to have a discussion of the
> tetrachord of Mercury.

As general discussion it would be, sure, but I don't think there's
anything that can be readily dismissed as 'not relevant' in terms of
providing abstract concepts to programmers. I've tried explaining
encapsulation to non-programmers using Reason's hardware rack
metaphor. I'm slowly seeing more and more interest in applying
hermeneutics to computer science, a discipline that arose out of the
study of religious texts.

We don't always know what we don't know. For that alone, I'd rather we
were more inclusive of topics of discussion than exclusionary.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Trivial Question

2011-09-29 Thread alex23
On Sep 29, 8:06 am, Chris Rebert  wrote:
> Try this:
>
> def trial():
>     class Foo(object):
>         def __init__(self):
>             print("Hello, world!")
>     Foo()
> trial()

While this will display "Hello, world!" in the way required, with a
slight adjustment you end up with something potentially a little more
useful:

def trial():
class Foo(object):
def __init__(self):
print("Hello, world!")
return Foo()

myfoo = trial()

You'll see the same behaviour, but now myfoo refers to the Foo()
object that was created inside trial. This makes trial an object
factory. If you return an uninstantiated Foo instead:

def trial():
class Foo(object):
def __init__(self):
print("Hello, world!")
return Foo

MyFoo = trial()
foo = MyFoo()

Then trial is a class factory, creating and returning a class.
Factories can be handy if you're wanting to create dynamic classes
based on run time information.

def reader_factory(format='json'):
  class Reader(object):
def __init__(self, file):
  self.file = file
if format == 'json':
  def process(self):
print 'json processing goes here'
elif format == 'html':
  def process(self):
print 'html processing goes here'
  return Reader

>>> JSONReader = reader_factory('json')
>>> j = JSONReader('file1')
>>> j.process()
json processing goes here

This is a trivial example which would probably be better handled by
subclasses, but is meant to be indicative of what's possible.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Benefit and belief

2011-09-29 Thread alex23
On Sep 30, 9:37 am, MRAB  wrote:
> rantingrick:
> """Since, like the bible the zen is self contradicting, any argument
> utilizing
> the zen can be defeated utilizing the zen."""
>
> alex23:
> """And like the Bible, the Zen was created by humans as a joke. If you're
> taking it too seriously, that's your problem."""

Strangely, calling the bible self-contradictory wasn't seen as
inflammatory...

Seeing the quotes again, I'm pretty sure I was intending to be
flippant _in reference to rantrantrantrick's comment_. Given that it
was a response to someone else referring to the bible _and_ it made a
point about the zen, I'm not entirely sure why my comment was OT.

Again, if you want to disagree with my remark, knock yourself out. If
you want to take it as a personal attack, then there's nothing I can
do to stop you. But do realise that it is _you_ who is interpreting it
as such, and then recall the provision your very own Christ stated
about judging the actions of others: within your own belief system
_it's not your right to do so_.

That never seems to reduce the moral outrage though...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-28 Thread alex23
On Sep 28, 10:12 pm, DevPlayer  wrote:
> Calling the Bible a joke is used to hurt people, not enlighten them.

Y'know, I wouldn't even bother responding to this if Xianists were as
open, forgiving and accepting as their messiah told them to be. It was
a *flippant remark*. If you want to establish intent, aggression and
religio-politico-philosophy from every throwaway remark made on the
internet, you're not really going to have much time for Python.

My belief system isn't your's. Hell, my belief system doesn't even
require that I have *any respect whatsoever* for your's. If it's okay
for Xianists to "suffer not a witch to live", then I'm going to assert
my making light jokes about those whose world view is in direct
opposition to mine isn't even comparable to that mentality.

from attitude import humour

(Since we're already fully derailed here, I've always preferred
Borges' suggestion that it was actually Judas who carried the full
weight of man's sins, given that his betrayal of Christ and inevitable
condemnation to hell was a necessity. Then again, I'm able to safely
view this as *allegory* and am genuinely interested in the opinions of
modern minds over something first begun by nomads millenia ago...)


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


Re: Suggested coding style

2011-09-27 Thread alex23
rantingrick  wrote:
> Since, like the bible
> the zen is self contradicting, any argument utilizing the zen can be
> defeated utilizing the zen.

And like the Bible, the Zen was created by humans as a joke. If you're
taking it too seriously, that's your problem.

> If however you want to learn about the accepted rules for formatting
> code then you need to read "PEP-8"! PEP 8 is our style guide.

PEP 8 is the _standard library style guide_. There's a difference.

> It is
> not perfect as i have pointed out on many occasions HOWEVER it is the
> only thing we have that keeps multiplicity from reproducing like
> leporidae.

Yes, save us from multiplicity, variety and difference. Nothing good
comes from them anyway.

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


Re: Wrote a new library - Comments and suggestions please!

2011-09-27 Thread alex23
Steven D'Aprano  wrote:
> I googled on "SAS PROC FREQ" and found this:
>
> http://support.sas.com/documentation/cdl/en/procstat/63104/HTML/defau...
>
> All the words are in English, but I have no idea what the function does, how
> you would call it, and what it returns. Would it have been so hard to show
> a couple of examples?

I'm currently arms deep in converting a handful of randomisation
algorithms written in SAS into Python. Pretty much ALL of the magic
happens behind cryptic SAS calls like this. I'm having more success
reverse-engineering the _results_ they produce and building something
Pythonic and comprehensible.

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


Re: install packages with pip to older Python versions

2011-09-26 Thread alex23
On Sep 27, 6:39 am, Jabba Laci  wrote:
> So, how can I install packages for a specific version of Python (here,
> v2.5)? With 2.7 I use "sudo pip install ".

It's amazing what you can find when you look at the documentation:
http://www.pip-installer.org/en/latest/index.html

"You can use pip install --upgrade SomePackage to upgrade to a newer
version, or pip install SomePackage==1.0.4 to install a very specific
version."

However, if you're not using virtualenv, I'd recommend looking at it
as well: http://pypi.python.org/pypi/virtualenv
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using python in web applications

2011-09-13 Thread alex23
On Sep 10, 1:54 pm, "Littlefield, Tyler"  wrote:
> I'm not feeling particularly masochistic, so I do not want to develop
> this project in PHP; essentially I'm looking to build a web-based MMO.

Google have been promoting the use of appengine along with HTML5 & JS
to produce games. One advantage of using GAE to host the server is it
takes care of the scaling for you.

I found these presentations fascinating:
http://cc-2011-html5-games.appspot.com/#1
http://io-2011-html5-games-hr.appspot.com/#1

This article covers the process in a little more depth:
http://clouddbs.blogspot.com/2011/02/how-to-write-html5-game-in-30-days-with.html

Google are also aggregating platform-specific info here:
http://code.google.com/games

Hope this helps (and let us know when you have something to show off!)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hello, and request for help with 'dynamic grids'

2011-09-05 Thread alex23
On Sep 5, 3:18 pm, Simon Cropper 
wrote:
> My investigations have generally found that windows/forms/data entry
> screen can be created for a specific table or view, but these are
> hard-wired during development. Is there anyway of rapidly defining the
> grid during runtime so any table can be viewed?

The commercial product Resolver One provides a grid/spreadsheet style
interface with Python scripting capabilities. I'm not sure of its
current licensing status but I believe it used to be free if used on
open source projects.

http://www.resolversystems.com/products/resolver-one/

Each spreadsheet itself is Python code; I think it should be quite do-
able to take something with introspective SQL capabilities like
SQLAlchemy and have it title columns and fill them with the correct
fields accordingly.

Hope this helps.


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


<    1   2   3   4   5   6   7   8   9   10   >