'Address already in use' ... with TCPServer

2009-01-29 Thread Mabooka-Mabooka Mbe-Mbe
   Hi all,

I bet everybody knows exactly what I am about to ask about:

'''
A server serves for a while, then drops on its knees, tries to restart, but... 
the port is busy, the TCP says "Address already in use".
'''

And, I think I know the answer: 
  setsockopt(REUSEADDR)...

The problem is: I am trying to use a very-high level far-away-from-socket class 
("TCPServer"); 
or to be 100% honest, - an even higher-level async version of it 
(like in  
http://www.python.org/doc/2.6/library/socketserver.html?highlight=tcpserver#asynchronous-mixins).


What I came up with so far is this:
>>> from SocketServer import *
>>> s = TCPServer( ('', 32123), None)
>>> dir(s)
['RequestHandlerClass', '__doc__', '__init__', '__module__', 'address_family', 
'allow_reuse_address', 'close_request', 'fileno', 'finish_request', 
'get_request', 'handle_error', 'handle_request', 'process_request', 
'request_queue_size', 'serve_forever', 'server_activate', 'server_address', 
'server_bind', 'server_close', 'socket', 'socket_type', 'verify_request']

Aha! My bet is (was):
>>> s.allow_reuse_address=1
should do the trick.

But it doesn't. (:___.

The question is: 
  how to set up TCPServer correctly to reuse the port right away.

Please give a hand.

I acknowledge that I am trying to hack it rather then looking at all the web 
1st: 
 sorry if I am spamming this list while good documentation exists. But does it?

:-#).


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


Re: Swapping values of two variables

2009-01-29 Thread Steven D'Aprano
On Thu, 29 Jan 2009 21:23:48 -0800, Kottiyath wrote:

> Is it possible to swap two floats without a variable?

In Python? Sure.

f = 1.23
g = 2.87
f, g = g, f



This idiom is independent of the types of the objects:

x = "hello world"
y = [1, 2.0, None, "xyz", {}]
x, y = y, x

In other languages? Hard to say. You *might* be able to use the XOR trick 
on floats, if you can access a float as a set of raw bytes. Same for 
strings, if they are the same length.

Assuming that the floats are of similar size, not NaNs or INFs, not 
subject to overflow or underflow, and not subject to rounding error, you 
can do this trick:

>>> f = 1.23
>>> g = 2.87
>>> f, g
(1.23, 2.8701)
>>> 
>>> f = f + g
>>> g = f - g
>>> f = f - g
>>> f, g
(2.8701, 1.2295)

But notice the round-off error in g. It gets worse if your values are of 
radically different sizes:


>>> f = 123.4
>>> g = 1.2e35
>>> f, g
(123.41, 1.2001e+35)
>>> f = f + g
>>> g = f - g
>>> f = f - g
>>> f, g
(1.2001e+35, 0.0)


This really is a trick, not something you should be doing in production 
code.



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


Re: is python Object oriented??

2009-01-29 Thread Chris Rebert
On Thu, Jan 29, 2009 at 10:25 PM, alex23  wrote:
> On Jan 30, 4:15 pm, Chris Rebert  wrote:
>> - Python does not support interfaces in the Java sense (although there
>> are a few third-party libraries that add such support); neither does
>> Smalltalk. Instead, both Smalltalk and Python use duck-typing to
>> similar effect. Seehttp://en.wikipedia.org/wiki/Duck_typing
>
> I haven't yet had reason to use them, but do Abstract Base Classes
> (introduced in 2.6/3.0) go some way to provide more defined interface
> support for Python? My assumption was that was what they'd generally
> be used for...

Ah, excellent point. I neglected to take ABCs into account. Smalltalk
did have those as well.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Swapping values of two variables

2009-01-29 Thread tony . clarke5
On Jan 30, 3:31 am, Steven D'Aprano
 wrote:
> On Thu, 29 Jan 2009 17:50:04 -0800, tony.clarke5 wrote:
> > On Jan 30, 12:29 am, Eric Kang  wrote:
> >> In python, I set:
>
> >> x=1
> >> y=3
>
> >> z = x
> >> x = y
> >> y = z
>
> >> This gave me 3 1, which are the values of x and y swapped. The
> >> following would have given me the same result: x, y = y, x
>
> >> But could the swapping be done using less extra memory than this? What
> >> is the minimum amount of extra memory required to exchange two 32-bit
> >> quantities? What would be the pseudocode that achieves this minimum?
>
> > How about:
> > def transpose(x, y):
> >     print x, y, 'becomes: ',
> >     x = x + y
> >     y = x - y
> >     x = x - y
> >     print x, ' ', y
>
> > transpose(1,3)
> > transpose (9,8)
>
> I'm not sure what the point of that function is. It doesn't actually swap
> its arguments:
>
> >>> x = 23
> >>> y = 42
> >>> transpose(x, y)
>
> 23 42 becomes:  42   23>>> x
> 23
> >>> y
>
> 42
>
> And it certainly doesn't save memory, as the original poster asked:
>
> >>> import dis
> >>> swap = compile('x, y = y, x', '', 'single')
> >>> dis.dis(swap)
>
>   1           0 LOAD_NAME                0 (y)
>               3 LOAD_NAME                1 (x)
>               6 ROT_TWO
>               7 STORE_NAME               1 (x)
>              10 STORE_NAME               0 (y)
>              13 LOAD_CONST               0 (None)
>              16 RETURN_VALUE
>
> >>> dis.dis(transpose)
>
>   2           0 LOAD_FAST                0 (x)
>               3 PRINT_ITEM
>               4 LOAD_FAST                1 (y)
>               7 PRINT_ITEM
>               8 LOAD_CONST               1 ('becomes: ')
>              11 PRINT_ITEM
>
>   3          12 LOAD_FAST                0 (x)
>              15 LOAD_FAST                1 (y)
>              18 BINARY_ADD
>              19 STORE_FAST               0 (x)
>
>   4          22 LOAD_FAST                0 (x)
>              25 LOAD_FAST                1 (y)
>              28 BINARY_SUBTRACT
>              29 STORE_FAST               1 (y)
>
>   5          32 LOAD_FAST                0 (x)
>              35 LOAD_FAST                1 (y)
>              38 BINARY_SUBTRACT
>              39 STORE_FAST               0 (x)
>
>   6          42 LOAD_FAST                0 (x)
>              45 PRINT_ITEM
>              46 LOAD_CONST               2 (' ')
>              49 PRINT_ITEM
>              50 LOAD_FAST                1 (y)
>              53 PRINT_ITEM
>              54 PRINT_NEWLINE
>              55 LOAD_CONST               0 (None)
>              58 RETURN_VALUE
>
> The compiled code of the transpose function *alone* (not including all
> the other associated parts) takes 59 bytes, or 472 bits.
>
> >>> len(transpose.func_code.co_code)
>
> 59
>
> Even if it worked, that's hardly using less memory than a direct swap.
>
> --
> Steven

Should have been more explicit about that: the values are swapped
within the namespace of the function, the function is just for
demonstration of the process. WIthout the function, this is the
result:
Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = -10
>>> y = 4
>>> x = x + y
>>> y = x - y
>>> x = x - y
>>> x
4
>>>
>>> y
-10
>>>
Need to think about swapping floats though.
Tony
--
http://mail.python.org/mailman/listinfo/python-list


Re: is python Object oriented??

2009-01-29 Thread alex23
On Jan 30, 4:15 pm, Chris Rebert  wrote:
> - Python does not support interfaces in the Java sense (although there
> are a few third-party libraries that add such support); neither does
> Smalltalk. Instead, both Smalltalk and Python use duck-typing to
> similar effect. Seehttp://en.wikipedia.org/wiki/Duck_typing

I haven't yet had reason to use them, but do Abstract Base Classes
(introduced in 2.6/3.0) go some way to provide more defined interface
support for Python? My assumption was that was what they'd generally
be used for...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-29 Thread r
On Jan 29, 11:53 pm, James Mills  wrote:
> On Fri, Jan 30, 2009 at 3:38 PM, r  wrote:
> > This observation leads me to two scientific and common sense synopsis.
> > Either nobody here gives a rats pa'toote about Python, and/or they are
> > all just a bunch of gutless worms too afraid to stand up to the 10 or
> > so Perl/Ruby leeches who's infestation slowly drains the life-blood
> > out of the Python Community, keeping it too weak to fight back.
> > 
>
> I for one am not e member of either the Perl or Ruby
> fan club - and I don't think I will ever be :) However I"m not
> going to go and start bagging those languages :) I prefer Python!
>
> I think you'll find a 3rd scenario:
>
> Python developers (those that develop Python)
> and Python programmers (those that use Python)
> just don't really care about politics, protest and
> all the rubbish that goes on in this list :)
>
> cheers
> James

I totally agree James. I not saying anybody should just go around
bashing this or that language, but i have seen many a ruffled feather
at the mere mention of Python's greatness. I could understand if
someone went over to the Perl group and started parroting off "Python
rules!, Perl sucks!". This should be condemned. But i have also seen
at this group very viscous attacks on people who just simply think
Python is a good language and want to tell their Python friends how
happy they are -- myself included.

People would call a happy user of Python a fanboy or a Python zealot.
This blows me away in the context of this group. check out this
thread:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/d15ed72979ba20f7/6195c98209dcc852?hl=en&lnk=gst&q=python+is+great#6195c98209dcc852

Here a happy python user shared his thoughts on the Python language.
He compared Python as "more readable" than Perl and by god he is right
about that, no sane person can honestly deny this fact. But like
always some angry responses and warnings followed that this person
should not criticize Perl, and veil threats were cast.

This is the madness i refer too.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rounding to the nearest 5

2009-01-29 Thread Steven D'Aprano
On Fri, 30 Jan 2009 00:24:47 -0500, D'Arcy J.M. Cain wrote:

> On Thu, 29 Jan 2009 16:06:09 -0800
> "todp...@hotmail.com"  wrote:
>> How can you make python round numbers to the nearest 5:
>>  
>> Example:
>>  
>> 3 => 0
>> 8 => 10
>> 23.2 => 20
>> 36 => 35
>> 51.5 => 50
> 
> That appears to be rounding to nearest 10, not 5.  Clarify your
> requirements first.

Look again. 36 => 35.



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


Re: new.instancemethod questions

2009-01-29 Thread schickb
On Jan 29, 8:51 pm, Brian Allen Vanderburg II
 wrote:
> You can also create a bound method and manually bind it to the
> instance.  This is easier
>
> import types
> a.f2 = types.MethodType(f1, a)
>
> a.f2() # prints object a

Ah thanks, that is what I was looking for. I missed that because
following types.MethodType in the docs is:

types.UnboundMethodType
An alternate name for MethodType

Which made me think it was a type for UnboundMethods (aka functions).
This:
>>> help(types.UnboundMethodType)

clears it up for me, but the docs are rather confusing.


> These may work for most uses, but both have a problem that happens if
> you need to make a copy of the instance.  When you copy it, the copies
> 'f1' will still call the function but using the old object
>
> a.f1() # prints object a
> b = copy.copy(a)
> b.f1() # still prints a
>

Ugh, that is a problem. I guess that means pickling won't work
either

Nope, "TypeError: can't pickle instancemethod objects". So does these
mean there is no way to create a method on an instance at runtime that
behaves just like a method that originated from the instance's class?

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


Re: is python Object oriented??

2009-01-29 Thread Chris Rebert
On Thu, Jan 29, 2009 at 9:56 PM, Hung Vo  wrote:

> I'm new to Python and also wondering about OOP in Python.
>
> I want to justify the above question (is Python Object-Oriented?).
> Does Python follow the concepts/practices of Encapsulation,
> Polymorphism and Interface, which are quite familiar to Java
> programmers?

If you're looking for a benchmark for object-orientedness, Smalltalk,
not Java, is the canonical language to compare against.

Anyway, to your three-pronged question:
- Yes, Python supports polymorphism. I find it hard to think of an
example of an OO language that doesn't.

- Python does not support interfaces in the Java sense (although there
are a few third-party libraries that add such support); neither does
Smalltalk. Instead, both Smalltalk and Python use duck-typing to
similar effect. See http://en.wikipedia.org/wiki/Duck_typing

- Python supports encapsulation. Prefixing an attribute/method with an
underscore indicates that other programmers should treat it as
'private'. However, unlike B&D languages, Python itself does nothing
to enforce this privacy, leaving it instead to the good judgement of
the programmer, under the philosophy that "We're all consenting adults
here". This allows people to meddle with internals, at their own risk,
if it ends up being absolutely necessary. The enforcement point is
largely academic anyway, as most languages' reflection APIs let you
poke at ostensibly "private" things.

Cheers,
Chris

P.S. You appear to have posted the same message 3 times(!), which is a
bit annoying for readers.

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: is python Object oriented??

2009-01-29 Thread Stephen Hansen
> I'm new to Python and also wondering about OOP in Python.
>
> I want to justify the above question (is Python Object-Oriented?).
> Does Python follow the concepts/practices of Encapsulation,
> Polymorphism and Interface, which are quite familiar to Java
> programmers?


Python does not enforce Encapsulation; but convention is extremely
successful here although there's some really loud people in this newsgroup
who state otherwise. Python programmers tend to be very well-behaved in this
regard and they do not poke into private API's -- unless /they have to/.
That's important: /have/ to. If they were not allowed, they'd be unable to
use that code. Internally in corporate software this is a complete
non-issue: and in any major project it should be a non-issue too. If you
follow basic convention (private is preceded by _) then it is extremely
clear if you're obeying encapsulation and if someone in your project breaks
it without a good reason-- refuse the addition.

Python is *extremely* polymorphic.

Python does not have any built-in "interface" capability, per se, but there
are add-on libraries that can be used to provide interface functionality if
you are doing a framework or large program that needs it.  Then again
"Interface" is a bit questionable as an "OOP Concept"; its used in some
implementations of an OOP language, and not used in anothers-- and what it
means in one can differ from what it means in another.

There's all kinds of other "concepts" of OOP that various people describe,
and generally you can do them all in Python.

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


Re: is python Object oriented??

2009-01-29 Thread alex23
On Jan 30, 4:00 pm, Hung Vo  wrote:
> Does Python follow the concepts/practices of Encapsulation,
> Polymorphism and Interface, which are quite familiar to Java
> programmers?

Well, it has the same _concepts_, but definitely not the same
practices/implementations. As they  say, Python is not Java :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: is python Object oriented??

2009-01-29 Thread Hung Vo
On Jan 30, 4:19 am, Michael Torrie  wrote:
> M Kumar wrote:
> > but still I am not clear of the execution of the code, when we write or
> > execute a piece of python code without defining class, predefined class
> > attributes are available (not all but __name__ and __doc__ are available).
> > does it mean anything to this topic. Is it necessory to have __module__,
> > __dict__ and __bases__ for a class object in python?
>
> I think you're confused as to what object-oriented means.  OO defines
> the internals of a language more than a particular programming paradigm.
>  Obviously python lets you program in a variety of paradigms, including
> procedural and event-driven, but it is all very much object-oriented.
> So ignore those that say python doesn't force you to use OOP, when in
> fact it's unavoidable.  It's just that you're not forced to place all
> your code in class definitions.  You don't need to because your code is
> already object-oriented in that you're manipulating objects and their
> attributes.
>
> As others have said, Python is an object-oriented language through and
> through, closer to Smalltalk in many ways, the grand-daddy of all OO
> languages.
>
> It appears that you are only really familiar with Java, and that leads
> to a number of interesting misconceptions about OO.  Java's bizarre OO
> requires everything to be in a class, which leads many people to believe
> this is what OO should be.  In fact Java is a bit odd when it comes to
> OO, as there are many things in Java that aren't in fact objects.  For
> example, primitives are intrinsic types and are not objects.
> Furthermore class definitions are not objects either, at least from the
> programmer's pov.  You can't manipulate them by standard means as you
> can in Smalltalk and Python.  In Smalltalk and Python a "class" is an
> object just as much as an instance of a class is an object which has a
> constructor factory method that returns instance objects.  Java also has
> very strange ways of doing singleton patterns.  You have to wrap
> singletons in class and define them as "static."  I think this was
> inherited from C++.
>
> The most basic object in a python script is the module object which
> represents the namespace of the current script.  In effect a module
> object is a singleton.  It has a few attributes, and you can use it to
> look up any of the objects it contains, such as functions, objects
> (so-called variables), classes, etc.  Everything in python is an object.
>  The statement:
>
> a = 4
>
> defines an integer object "4" and binds a name to it, 'a.'  You can even
> check to see what methods the object supports by doing:
>
> >>> dir(4)
>
> ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__',
> '__delattr__', '__div__', '__divmod__', '__doc__', '__float__',
> '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__',
> '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__',
> '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__',
> '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__',
> '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__',
> '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__',
> '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__',
> '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__']
>
> dir(a) would return the same thing.  As you can see, all the operators
> that can be performed with a number object are defined.  This little
> exercise alone should show you how much more object-oriented Python is
> than Java.
>
> Python's OO capabilities are really exposed when you start extending
> built-in types, or doing meta programming where you dynamically alter
> classes (and instance objects) on the fly.

I'm new to Python and also wondering about OOP in Python.

I want to justify the above question (is Python Object-Oriented?).
Does Python follow the concepts/practices of Encapsulation,
Polymorphism and Interface, which are quite familiar to Java
programmers?

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


Re: is python Object oriented??

2009-01-29 Thread Hung Vo
On Jan 30, 4:19 am, Michael Torrie  wrote:
> M Kumar wrote:
> > but still I am not clear of the execution of the code, when we write or
> > execute a piece of python code without defining class, predefined class
> > attributes are available (not all but __name__ and __doc__ are available).
> > does it mean anything to this topic. Is it necessory to have __module__,
> > __dict__ and __bases__ for a class object in python?
>
> I think you're confused as to what object-oriented means.  OO defines
> the internals of a language more than a particular programming paradigm.
>  Obviously python lets you program in a variety of paradigms, including
> procedural and event-driven, but it is all very much object-oriented.
> So ignore those that say python doesn't force you to use OOP, when in
> fact it's unavoidable.  It's just that you're not forced to place all
> your code in class definitions.  You don't need to because your code is
> already object-oriented in that you're manipulating objects and their
> attributes.
>
> As others have said, Python is an object-oriented language through and
> through, closer to Smalltalk in many ways, the grand-daddy of all OO
> languages.
>
> It appears that you are only really familiar with Java, and that leads
> to a number of interesting misconceptions about OO.  Java's bizarre OO
> requires everything to be in a class, which leads many people to believe
> this is what OO should be.  In fact Java is a bit odd when it comes to
> OO, as there are many things in Java that aren't in fact objects.  For
> example, primitives are intrinsic types and are not objects.
> Furthermore class definitions are not objects either, at least from the
> programmer's pov.  You can't manipulate them by standard means as you
> can in Smalltalk and Python.  In Smalltalk and Python a "class" is an
> object just as much as an instance of a class is an object which has a
> constructor factory method that returns instance objects.  Java also has
> very strange ways of doing singleton patterns.  You have to wrap
> singletons in class and define them as "static."  I think this was
> inherited from C++.
>
> The most basic object in a python script is the module object which
> represents the namespace of the current script.  In effect a module
> object is a singleton.  It has a few attributes, and you can use it to
> look up any of the objects it contains, such as functions, objects
> (so-called variables), classes, etc.  Everything in python is an object.
>  The statement:
>
> a = 4
>
> defines an integer object "4" and binds a name to it, 'a.'  You can even
> check to see what methods the object supports by doing:
>
> >>> dir(4)
>
> ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__',
> '__delattr__', '__div__', '__divmod__', '__doc__', '__float__',
> '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__',
> '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__',
> '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__',
> '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__',
> '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__',
> '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__',
> '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__',
> '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__']
>
> dir(a) would return the same thing.  As you can see, all the operators
> that can be performed with a number object are defined.  This little
> exercise alone should show you how much more object-oriented Python is
> than Java.
>
> Python's OO capabilities are really exposed when you start extending
> built-in types, or doing meta programming where you dynamically alter
> classes (and instance objects) on the fly.

I'm new to Python and also wondering about OOP in Python.

I want to justify the above question (is Python Object-Oriented?).
Does Python follow the concepts/practices of Encapsulation,
Polymorphism and Interface, which are quite familiar to Java
programmers?

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


Re: is python Object oriented??

2009-01-29 Thread Hung Vo
On Jan 30, 4:19 am, Michael Torrie  wrote:
> M Kumar wrote:
> > but still I am not clear of the execution of the code, when we write or
> > execute a piece of python code without defining class, predefined class
> > attributes are available (not all but __name__ and __doc__ are available).
> > does it mean anything to this topic. Is it necessory to have __module__,
> > __dict__ and __bases__ for a class object in python?
>
> I think you're confused as to what object-oriented means.  OO defines
> the internals of a language more than a particular programming paradigm.
>  Obviously python lets you program in a variety of paradigms, including
> procedural and event-driven, but it is all very much object-oriented.
> So ignore those that say python doesn't force you to use OOP, when in
> fact it's unavoidable.  It's just that you're not forced to place all
> your code in class definitions.  You don't need to because your code is
> already object-oriented in that you're manipulating objects and their
> attributes.
>
> As others have said, Python is an object-oriented language through and
> through, closer to Smalltalk in many ways, the grand-daddy of all OO
> languages.
>
> It appears that you are only really familiar with Java, and that leads
> to a number of interesting misconceptions about OO.  Java's bizarre OO
> requires everything to be in a class, which leads many people to believe
> this is what OO should be.  In fact Java is a bit odd when it comes to
> OO, as there are many things in Java that aren't in fact objects.  For
> example, primitives are intrinsic types and are not objects.
> Furthermore class definitions are not objects either, at least from the
> programmer's pov.  You can't manipulate them by standard means as you
> can in Smalltalk and Python.  In Smalltalk and Python a "class" is an
> object just as much as an instance of a class is an object which has a
> constructor factory method that returns instance objects.  Java also has
> very strange ways of doing singleton patterns.  You have to wrap
> singletons in class and define them as "static."  I think this was
> inherited from C++.
>
> The most basic object in a python script is the module object which
> represents the namespace of the current script.  In effect a module
> object is a singleton.  It has a few attributes, and you can use it to
> look up any of the objects it contains, such as functions, objects
> (so-called variables), classes, etc.  Everything in python is an object.
>  The statement:
>
> a = 4
>
> defines an integer object "4" and binds a name to it, 'a.'  You can even
> check to see what methods the object supports by doing:
>
> >>> dir(4)
>
> ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__',
> '__delattr__', '__div__', '__divmod__', '__doc__', '__float__',
> '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__',
> '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__',
> '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__',
> '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__',
> '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__',
> '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__',
> '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__',
> '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__']
>
> dir(a) would return the same thing.  As you can see, all the operators
> that can be performed with a number object are defined.  This little
> exercise alone should show you how much more object-oriented Python is
> than Java.
>
> Python's OO capabilities are really exposed when you start extending
> built-in types, or doing meta programming where you dynamically alter
> classes (and instance objects) on the fly.

I'm new to Python and also wondering about OOP in Python.

I want to justify the above question (is Python Object-Oriented?).
Does Python follow the concepts/practices of Encapsulation,
Polymorphism and Interface, which are quite familiar to Java
programmers?

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


Re: Module/Library That is Able To Use Cookies + Proxies?

2009-01-29 Thread Justin Ezequiel
On Jan 30, 12:06 pm, blackcapsoftw...@gmail.com wrote:
> I would like to do is be able to log into a site that uses cookies to
> store information about the user when logging in. This works fine and
> dandy with ClientCookie. Now, I want to be able to do so with a proxy,

urllib2

http://docs.python.org/library/urllib2.html#module-urllib2

class urllib2.HTTPCookieProcessor([cookiejar])
A class to handle HTTP Cookies.

class urllib2.ProxyHandler([proxies])¶
Cause requests to go through a proxy. If proxies is given, it must be
a dictionary mapping protocol names to URLs of proxies. The default is
to read the list of proxies from the environment variables . To
disable autodetected proxy pass an empty dictionary.

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


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-29 Thread James Mills
On Fri, Jan 30, 2009 at 3:38 PM, r  wrote:
> This observation leads me to two scientific and common sense synopsis.
> Either nobody here gives a rats pa'toote about Python, and/or they are
> all just a bunch of gutless worms too afraid to stand up to the 10 or
> so Perl/Ruby leeches who's infestation slowly drains the life-blood
> out of the Python Community, keeping it too weak to fight back.
> 

I for one am not e member of either the Perl or Ruby
fan club - and I don't think I will ever be :) However I"m not
going to go and start bagging those languages :) I prefer Python!

I think you'll find a 3rd scenario:

Python developers (those that develop Python)
and Python programmers (those that use Python)
just don't really care about politics, protest and
all the rubbish that goes on in this list :)

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


Re: Rounding to the nearest 5

2009-01-29 Thread Miles
On Thu, Jan 29, 2009 at 7:26 PM, Tim Chase wrote:
>> How can you make python round numbers to the nearest 5:
>>  Example:
>>  3 => 0
>> 8 => 10
>> 23.2 => 20
>> 36 => 35
>> 51.5 => 50
>
> I'm not sure *any* rounding system will give those results.

def bogoround(n):
n1 = n / 5.0
return int(round(n1) if n1 % 2 > 1 else n1) * 5

best-I-could-do-ly y'rs,
-Miles
--
http://mail.python.org/mailman/listinfo/python-list


Re: search speed

2009-01-29 Thread alex23
On Jan 30, 2:56 pm, r  wrote:
> On Jan 29, 5:51 pm, anders  wrote:
>
> > if file.findInFile("LF01"):
> > Is there any library like this ??
> > Best Regards
> > Anders
>
> Yea, it's called a for loop!
>
> for line in file:
>     if "string" in line:
>         do_this()

Which is what the OP is already doing:

> (Today i step line for line and check)

anders, you might have more luck with one of the text search libraries
out there:

PyLucene (although this makes Java a dependency): 
http://lucene.apache.org/pylucene/
Nucular: http://nucular.sourceforge.net/
mxTextTools: http://www.egenix.com/products/python/mxBase/mxTextTools/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-29 Thread r
On Jan 29, 6:21 pm, r  wrote:
> Also if anyone dares to mention that Python is a great language or
> better in this reguard or that, they get jumped and beat to death by
> their "so-called" brothers.

This observation leads me to two scientific and common sense synopsis.
Either nobody here gives a rats pa'toote about Python, and/or they are
all just a bunch of gutless worms too afraid to stand up to the 10 or
so Perl/Ruby leeches who's infestation slowly drains the life-blood
out of the Python Community, keeping it too weak to fight back.

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


Re: Swapping values of two variables

2009-01-29 Thread Grant Edwards
On 2009-01-30, MRAB  wrote:

>> What is the minimum amount of extra memory required to exchange two
>> 32-bit quantities? What would be the pseudocode that achieves this
>> minimum?
>
> x ^= y
> y ^= x
> x ^= y
>
> This is really only of use when working in assembly language.

And rarely then. ;)

[Readability counts everywhere.]

-- 
Grant

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


Re: Swapping values of two variables

2009-01-29 Thread Kottiyath
On Jan 30, 8:31 am, Steven D'Aprano
 wrote:
> On Thu, 29 Jan 2009 17:50:04 -0800, tony.clarke5 wrote:
> > On Jan 30, 12:29 am, Eric Kang  wrote:
> >> In python, I set:
>
> >> x=1
> >> y=3
>
> >> z = x
> >> x = y
> >> y = z
>
> >> This gave me 3 1, which are the values of x and y swapped. The
> >> following would have given me the same result: x, y = y, x
>
> >> But could the swapping be done using less extra memory than this? What
> >> is the minimum amount of extra memory required to exchange two 32-bit
> >> quantities? What would be the pseudocode that achieves this minimum?
>
> > How about:
> > def transpose(x, y):
> >     print x, y, 'becomes: ',
> >     x = x + y
> >     y = x - y
> >     x = x - y
> >     print x, ' ', y
>
> > transpose(1,3)
> > transpose (9,8)
>
> I'm not sure what the point of that function is. It doesn't actually swap
> its arguments:
>
> >>> x = 23
> >>> y = 42
> >>> transpose(x, y)
>
> 23 42 becomes:  42   23>>> x
> 23
> >>> y
>
> 42
>
> And it certainly doesn't save memory, as the original poster asked:
>
> >>> import dis
> >>> swap = compile('x, y = y, x', '', 'single')
> >>> dis.dis(swap)
>
>   1           0 LOAD_NAME                0 (y)
>               3 LOAD_NAME                1 (x)
>               6 ROT_TWO
>               7 STORE_NAME               1 (x)
>              10 STORE_NAME               0 (y)
>              13 LOAD_CONST               0 (None)
>              16 RETURN_VALUE
>
> >>> dis.dis(transpose)
>
>   2           0 LOAD_FAST                0 (x)
>               3 PRINT_ITEM
>               4 LOAD_FAST                1 (y)
>               7 PRINT_ITEM
>               8 LOAD_CONST               1 ('becomes: ')
>              11 PRINT_ITEM
>
>   3          12 LOAD_FAST                0 (x)
>              15 LOAD_FAST                1 (y)
>              18 BINARY_ADD
>              19 STORE_FAST               0 (x)
>
>   4          22 LOAD_FAST                0 (x)
>              25 LOAD_FAST                1 (y)
>              28 BINARY_SUBTRACT
>              29 STORE_FAST               1 (y)
>
>   5          32 LOAD_FAST                0 (x)
>              35 LOAD_FAST                1 (y)
>              38 BINARY_SUBTRACT
>              39 STORE_FAST               0 (x)
>
>   6          42 LOAD_FAST                0 (x)
>              45 PRINT_ITEM
>              46 LOAD_CONST               2 (' ')
>              49 PRINT_ITEM
>              50 LOAD_FAST                1 (y)
>              53 PRINT_ITEM
>              54 PRINT_NEWLINE
>              55 LOAD_CONST               0 (None)
>              58 RETURN_VALUE
>
> The compiled code of the transpose function *alone* (not including all
> the other associated parts) takes 59 bytes, or 472 bits.
>
> >>> len(transpose.func_code.co_code)
>
> 59
>
> Even if it worked, that's hardly using less memory than a direct swap.
>
> --
> Steven

Is it possible to swap two floats without a variable?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rounding to the nearest 5

2009-01-29 Thread D'Arcy J.M. Cain
On Thu, 29 Jan 2009 16:06:09 -0800
"todp...@hotmail.com"  wrote:
> How can you make python round numbers to the nearest 5:
>  
> Example:
>  
> 3 => 0
> 8 => 10
> 23.2 => 20
> 36 => 35
> 51.5 => 50

That appears to be rounding to nearest 10, not 5.  Clarify your
requirements first.

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: libsudo ?

2009-01-29 Thread Brian Allen Vanderburg II

linuxguy...@gmail.com wrote:

Does anyone know where I would find libsudo ?
  

http://sourceforge.net/projects/libsudo

If you had the choice of using pexpect or libsudo, which would you use ?
  
libsudo does all the work for you of executing sudo, checking for the 
expected responses and all.  If all you need it for is to use sudo from 
Python I suspect it would be easier than pexpect.


It is a C library however, so after being compiled and installed, you 
will need to use ctypes to use it.  It is very simple, as the only 
function to deal with is:


int runAs( char* command, char* password, char* user, int invalidate );

Thanks

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

Brian Vanderburg II
--
http://mail.python.org/mailman/listinfo/python-list


Re: new.instancemethod questions

2009-01-29 Thread Brian Allen Vanderburg II

schi...@gmail.com wrote:

On Jan 29, 7:38 pm, Mel  wrote:
  

schickb wrote:


I'd like to add bound functions to instances, and found the
instancemethod function in the new module. A few questions:
  
1. Why is instancemethod even needed? Its counter-intuitive (to me at

least) that assigning a function to a class results in bound functions
its instances, while assigning directly to instances does not create a
bound function. So why doesn't assigning a function to an instance
attribute result in a function bound to that instance?
  

If I understand you correctly, rebinding to the instance would break code
like:

myfakefile.write = sys.stdout.write

where the intent would be to redirect any output through myfakefile straight
to sys.stdout.  The code for the sys.stdout.write function would never find
the attributes it needed in the instance of myfakefile.  To do this,
methods have to stay bound to their proper instances.




1. I'm thinking about assigning free non-bound functions. Like:

class A(object):
   pass

def func(self):
   print repr(self)

a = A()
a.func = func  # Why doesn't this automatically create a bound
function (aka method)?
  
Actually I found out the implementation of why it doesn't after messing 
around some more.  If an attribute is found in the instance dictionary, 
even if it is a descriptor it's __get__ doesn't get called, only if it 
is found in the class dictionary of the class or base classes.  This 
makes it where you can store a function in the instance to be called 
later as a function for some useful purpose, for example two different 
instances of an object could use different sorting functions:


# sort functions are responsible for sorting which mutation is the least 
and most fit

def fitness1(v1, v2):
   # use one technique to determine which is more fit

def fitness2(v1, v2):
   # use another technique to determine which is more fit

... # more fitness functions

class Environment:
   def __init__(self, fitness, ...):
  self.fitness_func = fitness
  ...
   ...

# create environments, each one has different fitness function
a = Environment(fitness1)
b = Environment(fitness2)


Now when it is time to kill off the least fit of the genetic mutations, 
each environment can sort which is the least and most fit in different ways.


2. And what is the preferred way to do this if the "new" module and
its instancemethod function are depreciated?

  

Most of the code I see does this with a closure something like this:

def AddMethod(obj, func, name=None):
   if name is None:
  name = func.__name__

   def method(*args, **kwargs):
  return func(obj, *args, **kwargs)
   setattr(obj, name, method)

class MyClass(object):
   pass

def f1(self):
   print self

a = MyClass()
AddMethod(a, f1)

a.f1() # prints object a

You can also create a bound method and manually bind it to the 
instance.  This is easier


import types
a.f2 = types.MethodType(f1, a)

a.f2() # prints object a


These may work for most uses, but both have a problem that happens if 
you need to make a copy of the instance.  When you copy it, the copies 
'f1' will still call the function but using the old object


a.f1() # prints object a
b = copy.copy(a)
b.f1() # still prints a



Brian Vanderburg II
--
http://mail.python.org/mailman/listinfo/python-list


Re: search speed

2009-01-29 Thread r
On Jan 29, 5:51 pm, anders  wrote:
> if file.findInFile("LF01"):
> Is there any library like this ??
> Best Regards
> Anders

Yea, it's called a for loop!

for line in file:
if "string" in line:
do_this()
--
http://mail.python.org/mailman/listinfo/python-list


libsudo ?

2009-01-29 Thread Linuxguy123
Does anyone know where I would find libsudo ?

If you had the choice of using pexpect or libsudo, which would you use ?

Thanks

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


Re: error on building 2.6.1. (_ctypes)

2009-01-29 Thread Gabriel Genellina
En Thu, 29 Jan 2009 22:19:18 -0200, Bernard Rankin   
escribió:


I am trying to build python 2.6 on a machine (web server) that I do not  
have root access to. (has 2.4 installed)


Python 2.5 builds fine, but I am getting an error when I run "make" for  
2.6.1.



/home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3941:  
error: syntax error before '*' token
/home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3942:  
warning: function declaration isn't a prototype
/home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c: In  
function `CFuncPtr_nonzero':
/home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3943:  
error: `self' undeclared (first use in this function)


Mmm... my 2.6.1 source show different line numbers, maybe you should check  
it's the right file?



Failed to find the necessary bits to build these modules:
_tkinter   bsddb185   sunaudiodev
Failed to build these modules:
_ctypes

~~~

I am guessing that I don't need tkinter or sunaudiodev, but what about  
the others?


bsddb185 is just for compatibility with the old Berkeley DB. I'd be  
worried just by ctypes - and only if you actually require it.


--
Gabriel Genellina

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


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-29 Thread r
On Jan 29, 9:01 pm, alex23  wrote:
> Seriously, how -old- are you? Twelve? Thirteen?

Ah, my good friend alex23.
Somehow -- when i was writing this post -- i knew you would drop in
and i swear i do not have any ESP abilities -- somehow i just knew.

While your here why don't we take a walk down memory lane. Let's go
back to our first encounter -- Yes, that crazy thread(i won't utter
the title here). Seems i was promoting the inclusion of the Python
language in a revolutionary and promising application and you were
very upset about it. Why, i really don't know because you never told
me. The only thing i can remember is you wishing me dead -- if i
recall your wish was to cut off oxygen supply to my brain.

I can't help but wonder of the devious thoughts that toil away in your
demented little mind right now. Of what demise shall i suffer this
time alex23. But please alex, at least -try- to be a little more
creative, if i am to meet my end, i would hate for it to be some worn-
out old cliche'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-29 Thread Ben Finney
alex23  writes:

> On Jan 30, 10:21 am, r  wrote:
> > I been around the list for a while and rubbed sholders with some
> > pythonistas(some you would not beleieve if i told you) and i just
> > don't see a community spirit here.
> 
> Seriously, how -old- are you? Twelve? Thirteen?

Please stop baiting people. If you find someone to be annoying, don't
incite them. Either find a way to direct the discussion to something
more constructive, or filter it out.

-- 
 \ “Pinky, are you pondering what I'm pondering?” “I think so, |
  `\ Brain, but how will we get a pair of Abe Vigoda's pants?” |
_o__)   —_Pinky and The Brain_ |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Module/Library That is Able To Use Cookies + Proxies?

2009-01-29 Thread blackcapsoftware
Hey guys,

I have been search the net for a bit now and can't find anything. What
I would like to do is be able to log into a site that uses cookies to
store information about the user when logging in. This works fine and
dandy with ClientCookie. Now, I want to be able to do so with a proxy,
does anyone have any suggestions, or libraries?

Any help is greatly appreciated.

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


Re: Using equals operator without changing reference pointer

2009-01-29 Thread Terry Reedy

Erik Max Francis wrote:

mark.sea...@gmail.com wrote:


Is there a way to lock down myInst so that it still refers to the
original object, and is there some special member that will allow me
to override the equals operator in this case?  Or is that simply
blasphemous against everything Python holds sacred?  Certainly there
is some keyword that I don't know about.


No.  The assignment operator with a bare name on the left hand side is 
not overridable.


So that 'name = ob' *always* binds name to ob.  That is one thing one 
can depend on when reading Python code.


You can override attribute access, however, with 
.__getattr__/.__getattribute__.


I presume that you have over-riden __setitem__ in addition to 
__getitem__ so that myOb[0] = 1 sets the bit. You could add a branch to 
__setitem__ (or define __setslice__ in 2.x) so that myOb[:] = 0x55 does 
just what you want it to -- set all bits.  Being able to get/set 
contiguous bits might be something you want anyway.


tjr

PS. When asking about internal details, specify version of interest, as 
there have been minor changes.



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


Re: new.instancemethod questions

2009-01-29 Thread schickb
On Jan 29, 7:38 pm, Mel  wrote:
> schickb wrote:
> > I'd like to add bound functions to instances, and found the
> > instancemethod function in the new module. A few questions:
>
> > 1. Why is instancemethod even needed? Its counter-intuitive (to me at
> > least) that assigning a function to a class results in bound functions
> > its instances, while assigning directly to instances does not create a
> > bound function. So why doesn't assigning a function to an instance
> > attribute result in a function bound to that instance?
>
> If I understand you correctly, rebinding to the instance would break code
> like:
>
> myfakefile.write = sys.stdout.write
>
> where the intent would be to redirect any output through myfakefile straight
> to sys.stdout.  The code for the sys.stdout.write function would never find
> the attributes it needed in the instance of myfakefile.  To do this,
> methods have to stay bound to their proper instances.
>

1. I'm thinking about assigning free non-bound functions. Like:

class A(object):
   pass

def func(self):
   print repr(self)

a = A()
a.func = func  # Why doesn't this automatically create a bound
function (aka method)?


2. And what is the preferred way to do this if the "new" module and
its instancemethod function are depreciated?


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


Re: Rounding to the nearest 5

2009-01-29 Thread Steven D'Aprano
On Thu, 29 Jan 2009 18:26:34 -0600, Tim Chase wrote:

>> How can you make python round numbers to the nearest 5:
>>  
>> Example:
>>  
>> 3 => 0
>> 8 => 10
>> 23.2 => 20
>> 36 => 35
>> 51.5 => 50
> 
> I'm not sure *any* rounding system will give those results.

Round towards zero.


> 3 should round up to 5 (not down to 0) 

That would be round to nearest.



>  result = int(round(x / 5.0) * 5)

I think that should work. It even works for negative values:


>>> int(round(-2.2 / 5.0) * 5)
0
>>> int(round(-2.7 / 5.0) * 5)
-5




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


Re: is python Object oriented??

2009-01-29 Thread Chris Rebert
On Thu, Jan 29, 2009 at 7:31 PM, Steven D'Aprano
 wrote:
> On Thu, 29 Jan 2009 02:25:57 -0800, Chris Rebert wrote:
>
>> In addition to methods, Python has functions, which are not associated
>> with a class
>
> Yes they are.
>
 (lambda: None).__class__
> 
>
> The function type itself has a class:
>
 (lambda: None).__class__.__class__
> 

I think we're now quibbling over the interpretation of "associated".
My intention was to contrast how methods and classmethods are stored
and accessed through the class they are defined in (or grafted onto),
whereas plain functions are not (instance/class variables that happen
to hold functions notwithstanding).

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: naming and binding (subtle Python 3 change)

2009-01-29 Thread Terry Reedy

Alan G Isaac wrote:

The example give at
http://docs.python.org/reference/executionmodel.html#naming-and-binding
remains unchanged at
http://docs.python.org/3.0/reference/executionmodel.html#naming-and-binding
but the change to Python 3 list comprehensions now means the example
will fail even with list comprehension syntax.  Should the example be
changed to make that clear?


http://bugs.python.org/issue5106

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


Re: new.instancemethod questions

2009-01-29 Thread Mel
schickb wrote:

> I'd like to add bound functions to instances, and found the
> instancemethod function in the new module. A few questions:
> 
> 1. Why is instancemethod even needed? Its counter-intuitive (to me at
> least) that assigning a function to a class results in bound functions
> its instances, while assigning directly to instances does not create a
> bound function. So why doesn't assigning a function to an instance
> attribute result in a function bound to that instance?

If I understand you correctly, rebinding to the instance would break code
like:

myfakefile.write = sys.stdout.write

where the intent would be to redirect any output through myfakefile straight
to sys.stdout.  The code for the sys.stdout.write function would never find
the attributes it needed in the instance of myfakefile.  To do this,
methods have to stay bound to their proper instances.

Mel.

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


Re: is python Object oriented??

2009-01-29 Thread Steven D'Aprano
On Thu, 29 Jan 2009 02:25:57 -0800, Chris Rebert wrote:

> In addition to methods, Python has functions, which are not associated
> with a class 

Yes they are.

>>> (lambda: None).__class__


The function type itself has a class:

>>> (lambda: None).__class__.__class__



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


Re: Swapping values of two variables

2009-01-29 Thread Steven D'Aprano
On Thu, 29 Jan 2009 17:50:04 -0800, tony.clarke5 wrote:

> On Jan 30, 12:29 am, Eric Kang  wrote:
>> In python, I set:
>>
>> x=1
>> y=3
>>
>> z = x
>> x = y
>> y = z
>>
>> This gave me 3 1, which are the values of x and y swapped. The
>> following would have given me the same result: x, y = y, x
>>
>> But could the swapping be done using less extra memory than this? What
>> is the minimum amount of extra memory required to exchange two 32-bit
>> quantities? What would be the pseudocode that achieves this minimum?
> 
> How about:
> def transpose(x, y):
> print x, y, 'becomes: ',
> x = x + y
> y = x - y
> x = x - y
> print x, ' ', y
> 
> transpose(1,3)
> transpose (9,8)


I'm not sure what the point of that function is. It doesn't actually swap 
its arguments:

>>> x = 23
>>> y = 42
>>> transpose(x, y)
23 42 becomes:  42   23
>>> x
23
>>> y
42

And it certainly doesn't save memory, as the original poster asked:


>>> import dis
>>> swap = compile('x, y = y, x', '', 'single')
>>> dis.dis(swap)
  1   0 LOAD_NAME0 (y)
  3 LOAD_NAME1 (x)
  6 ROT_TWO
  7 STORE_NAME   1 (x)
 10 STORE_NAME   0 (y)
 13 LOAD_CONST   0 (None)
 16 RETURN_VALUE


>>> dis.dis(transpose)
  2   0 LOAD_FAST0 (x)
  3 PRINT_ITEM
  4 LOAD_FAST1 (y)
  7 PRINT_ITEM
  8 LOAD_CONST   1 ('becomes: ')
 11 PRINT_ITEM

  3  12 LOAD_FAST0 (x)
 15 LOAD_FAST1 (y)
 18 BINARY_ADD
 19 STORE_FAST   0 (x)

  4  22 LOAD_FAST0 (x)
 25 LOAD_FAST1 (y)
 28 BINARY_SUBTRACT
 29 STORE_FAST   1 (y)

  5  32 LOAD_FAST0 (x)
 35 LOAD_FAST1 (y)
 38 BINARY_SUBTRACT
 39 STORE_FAST   0 (x)

  6  42 LOAD_FAST0 (x)
 45 PRINT_ITEM
 46 LOAD_CONST   2 (' ')
 49 PRINT_ITEM
 50 LOAD_FAST1 (y)
 53 PRINT_ITEM
 54 PRINT_NEWLINE
 55 LOAD_CONST   0 (None)
 58 RETURN_VALUE



The compiled code of the transpose function *alone* (not including all 
the other associated parts) takes 59 bytes, or 472 bits.

>>> len(transpose.func_code.co_code)
59

Even if it worked, that's hardly using less memory than a direct swap.



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


Re: Swapping values of two variables

2009-01-29 Thread Steven D'Aprano
On Thu, 29 Jan 2009 16:29:11 -0800, Eric Kang wrote:

> In python, I set:
> 
> x=1
> y=3
> 
> z = x
> x = y
> y = z
> 
> 
> This gave me 3 1, which are the values of x and y swapped. The following
> would have given me the same result: x, y = y, x

Yes.


> But could the swapping be done using less extra memory than this? What
> is the minimum amount of extra memory required to exchange two 32-bit
> quantities? What would be the pseudocode that achieves this minimum?

Ints in Python are *objects*, not 32-bit quantities. An int is 12 bytes 
(96 bits) in size; a long will use as much memory as needed. If your 
application needs to optimize a swap of two ints, then Python is probably 
going to be much too memory-intensive for you.

(But my money is on you doing premature optimization.)



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


Re: Using equals operator without changing reference pointer

2009-01-29 Thread Erik Max Francis

mark.sea...@gmail.com wrote:


Is there a way to lock down myInst so that it still refers to the
original object, and is there some special member that will allow me
to override the equals operator in this case?  Or is that simply
blasphemous against everything Python holds sacred?  Certainly there
is some keyword that I don't know about.


No.  The assignment operator with a bare name on the left hand side is 
not overridable.


You can override attribute access, however, with 
.__getattr__/.__getattribute__.


--
Erik Max Francis && m...@alcyone.com && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
  The perfection of innocence, indeed, is madness.
   -- Arthur Miller
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-29 Thread alex23
On Jan 30, 10:21 am, r  wrote:
> I been around the list for a while and rubbed sholders with some
> pythonistas(some you would not beleieve if i told you) and i just
> don't see a community spirit here.

Seriously, how -old- are you? Twelve? Thirteen?
--
http://mail.python.org/mailman/listinfo/python-list


Using equals operator without changing reference pointer

2009-01-29 Thread mark . seagoe
I know this may be asking too much of Python, but you never know
unless you ask...

So now having a class that can be treated like an int as far as math
upon the instance name, and can be treated as in HDL simulators,
allowing bitslice and bitselect ops, I was stoked.  Also reading back
the instance name returns the int, rather than text about the class
name and location in memory.  But... it would be wonderful if there
was a way to assign a value without using any .member notation... if
there were a way for me to specify that the reference would never
change.  For example:

>>> myInst = MyClass(0xAA)
>>> myInst
170
>>> myInst[0]  # <== MyClass can do bit selection
0
>>> myInst = 0x55   # <== gets reassigned
>>> myInst[0]# <== this is where it would choke
1 # <== this is the answer I would want

Is there a way to lock down myInst so that it still refers to the
original object, and is there some special member that will allow me
to override the equals operator in this case?  Or is that simply
blasphemous against everything Python holds sacred?  Certainly there
is some keyword that I don't know about.

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


new.instancemethod questions

2009-01-29 Thread schickb
I'd like to add bound functions to instances, and found the
instancemethod function in the new module. A few questions:

1. Why is instancemethod even needed? Its counter-intuitive (to me at
least) that assigning a function to a class results in bound functions
its instances, while assigning directly to instances does not create a
bound function. So why doesn't assigning a function to an instance
attribute result in a function bound to that instance?

2. The 2.6 docs say the new module is depreciated and refers to the
types module instead. But I haven't found a way to create bound
functions using the types module. Am I just missing something?

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


Re: Swapping values of two variables

2009-01-29 Thread tony . clarke5
On Jan 30, 12:29 am, Eric Kang  wrote:
> In python, I set:
>
> x=1
> y=3
>
> z = x
> x = y
> y = z
>
> This gave me 3 1, which are the values of x and y swapped.
> The following would have given me the same result:
> x, y = y, x
>
> But could the swapping be done using less extra memory than this? What is the 
> minimum amount of extra memory required to exchange two 32-bit quantities? 
> What would be the pseudocode that achieves this minimum?

How about:
def transpose(x, y):
print x, y, 'becomes: ',
x = x + y
y = x - y
x = x - y
print x, ' ', y

transpose(1,3)
transpose (9,8)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Sloooooowwwww WSGI restart

2009-01-29 Thread Graham Dumpleton
On Jan 30, 9:53 am, Ron Garret  wrote:
> In article <498171a5$0$3681$426a7...@news.free.fr>,
>  Bruno Desthuilliers 
>
>  wrote:
> > Ron Garret a écrit :
> > > In article ,
> > >  Aleksandar Radulovic  wrote:
> > (snip)
> > >> Secondly, why are you restarting apache after code changes? In normal
> > >> circumstances, you shouldn't have to do that.
>
> > > I thought (and experiment confirms) that only the main WSGI app file
> > > gets reloaded automatically when it changes, not the libraries.
>
> > Depends on how you configure mod_wsgi. Read the part about "Process
> > Reloading Mechanism" here:
> >http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode
>
> I'm running Debian Etch, which means I have an older version of
> mod_wsgi, which means I don't have the process reloading mechanism.

Back port available at:

  http://packages.debian.org/etch-backports/libapache2-mod-wsgi

Graham

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


Re: More mod_wsgi weirdness: process restarts on redirect

2009-01-29 Thread Graham Dumpleton
On Jan 30, 11:01 am, Ron Garret  wrote:
> In article ,
>  Joshua Kugler  wrote:
>
> > Ron Garret wrote:
> > > My question is: is this supposed to be happening?  Or is this an
> > > indication that something is wrong, and if so, what?
>
> > You are probably just hitting a different instance of Apache, thus the
> > different process ID.
>
> Yep, that's what it turned out to be.  I thought I had a
> WSGIDaemonProcess processes=1 directive in my config, but I had it in
> the wrong place (a different vhost) so it wasn't actually active.
> http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading
> But that leaves me wondering why the redirect would reliably trigger
> switching processes.  The reason I thought that I had the correct
> configuration and only had one process is that when I reloaded the
> non-redirected page I *always* got the same process ID.  How 
> doesmod_wsgidecide which process  (and which thread for that matter) to use?

Details on process/threading in mod_wsgi available at:

  http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading

When using WSGIDaemonProcess directive, if you want a single process
it is better to allow it to default to a single process and not have
'processes=1'. As soon as you say 'processes=1' it will trigger
wsgi.multiprocess to be True rather than default of False. This may
sound counter intuitive, but is a little back door to allow
wsgi.multiprocess to be set to True somehow when distributing an
application across a cluster of machines where it does need to be True
even if each machine only has a single process for that application.
Tthat wsgi.multiprocess is True will not usually matter unless you are
trying to use debugging middleware that require that there only be a
single process.

As to why you were getting a different process, because you were
actually running in embedded mode due to WSGIDaemonProcess/
WSGIProcessGroup being in wrong context, then what process was used
was really up to Apache and how it works. Specifically it can have
multiple processes that can listen on the HTTP port (80). Because only
one should be listening at a time it uses a cross process mutex lock
to mediate access. When a process handles a request, it gives up the
lock. If using worker MPM then another thread in same process may get
lock, or for either worker MPM or prefork MPM, then another process
could get it. Which actually gets it is a bit indeterminate as simply
depends on which process the operating system lets have the lock next.
So, there is no strict rule one can say as to who would get it next.

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


Re: UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 10442: character maps to

2009-01-29 Thread John Machin
Benjamin Kaplan  case.edu> writes:

> First of all, you're right that might be confusing. I was thinking of
auto-detect as in "check the platform and locale and guess what they usually
use". I wasn't thinking of it like the web browsers use it.I think it uses
locale.getpreferredencoding().

You're probably right. I'd forgotten about locale.getpreferredencoding(). I'll
raise a request on the bug tracker to get some more precise wording in the
open() docs.

> On my machine, I get sys.getpreferredencoding() == 'utf-8' and
locale.getdefaultencoding()== 'cp1252'. 

sys <-> locale ... +1 long-range transposition typo of the year :-)

> If you check my response to Anjanesh's comment, I mentioned that he should
either find out which encoding it is in particular or he should open the file in
binary mode. I suggested utf-8 and latin1 because those are the most likely
candidates for his file since cp1252 was already excluded.

The OP is on a Windows machine. His file looks like a source code file. He is
unlikely to be creating latin1 files himself on a Windows box. Under the
hypothesis that he is accidentally or otherwise reading somebody else's source
files as data, it could be any encoding. In one package with which I'm familiar,
the encoding is declared as cp1251 in every .py file; AFAICT the only file with
non-ASCII characters is an example script containing his wife's name!

The OP's 0x9d is a defined character in code pages 1250, 1251, 1256, and 1257 --
admittedly all as implausible as the latin1 control character.

> Looking at a character map, 0x9d is a control character in latin1, so the page
is probably UTF-8 encoded. Thinking about it now, it could also be MacRoman but
that isn't as common as UTF-8.

Late breaking news: I presume you can see two instances of U+00DD (LATIN CAPITAL
LETTER Y WITH ACUTE) in the OP's report 
"query":"0 1»Ý \u2021 0\u201a0 \u2021»Ý","

Well, u'\xdd'.encode('utf8') is '\xc3\x9d' ... the Bayesian score for utf8 just
went up a notch.

The preceding character U+00BB (looks like >>) doesn't cause an exception
because 0xBB unlike 0x9D is defined in cp1252.

Curiously looking at the \u escape sequences:
\u2021 is "double dagger", \u201a is "single low-9 quotation mark" ... what
appears to be the value part of an item in a hard-coded dictionary is about as
comprehensible as the Voynich manuscript.

Trouble with cases like this is as soon as they become interesting, the OP often
snatches somebody's one-liner that "works" (i.e. doesn't raise an exception),
makes a quick break for the county line, and they're not seen again :-)

Cheers,
John


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


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-29 Thread Giampaolo Rodola'
> Where are the community projects supporting Python? -- besides the
> core devlopment.

http://pypi.python.org/pypi

...which accidentally says "There are currently 5597 packages here."
Not bad uh?



--- Giampaolo
http://code.google.com/p/pyftpdlib
--
http://mail.python.org/mailman/listinfo/python-list


Re: Swapping values of two variables

2009-01-29 Thread MRAB

Eric Kang wrote:

In python, I set:

x=1
y=3

z = x
x = y
y = z


This gave me 3 1, which are the values of x and y swapped.
The following would have given me the same result:
x, y = y, x

But could the swapping be done using less extra memory than this?
What is the minimum amount of extra memory required to exchange two
32-bit quantities? What would be the pseudocode that achieves this
minimum?


x ^= y
y ^= x
x ^= y

This is really only of use when working in assembly language.
--
http://mail.python.org/mailman/listinfo/python-list


Swapping values of two variables

2009-01-29 Thread Eric Kang
In python, I set:

x=1
y=3

z = x
x = y
y = z


This gave me 3 1, which are the values of x and y swapped.
The following would have given me the same result:
x, y = y, x



But could the swapping be done using less extra memory than this? What is the 
minimum amount of extra memory required to exchange two 32-bit quantities? What 
would be the pseudocode that achieves this minimum?
--
http://mail.python.org/mailman/listinfo/python-list


naming and binding (subtle Python 3 change)

2009-01-29 Thread Alan G Isaac

The example give at
http://docs.python.org/reference/executionmodel.html#naming-and-binding
remains unchanged at
http://docs.python.org/3.0/reference/executionmodel.html#naming-and-binding
but the change to Python 3 list comprehensions now means the example
will fail even with list comprehension syntax.  Should the example be
changed to make that clear?

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


Re: verilog like class w/ bitslicing & int/long classtype

2009-01-29 Thread Marc 'BlackJack' Rintsch
On Fri, 30 Jan 2009 00:25:03 +0100, Stef Mientki wrote:

> try this:
> 
> class MyRegClass ( int ) :
>   def __init__ ( self, value ) :
> self.Value = value
>   def __repr__ ( self ) :
> line = hex ( self.Value )
> line = line [:2] + line [2:].upper()
> return line

def __repr__(self):
return '0x%X' % self.value

>   __str__ = __repr__

This is unnecessary, the fallback of `__str__` is `__repr__` already.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: verilog like class w/ bitslicing & int/long classtype

2009-01-29 Thread mark . seagoe
On Jan 29, 3:13 pm, Stef Mientki  wrote:
> mark.sea...@gmail.com wrote:
> > Thanks.  So far these solutions will return strings.  So I can't
> > really treat it like a variable, yet still perform bitslice on it,
> > since I need a special class to do bitslice and bit selection, but as
> > soon as I try to pass it into some other function to check a bit, I
> > gotta then do another operation to convert back to a variable.
>
> > So I can get it to a point where I can do shadow_register[3] and get
> > the value of any bit, or I can do shadow_register[4:2] and get a
> > bitslice, and I can write them just as easily at this point.  If I add
> > the __new__ method into the class, the instance obj becomes int, but
> > is no longer slicable.  I think it looks like I can't have it both
> > ways.
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> there are a few vhdl projects,
> can't find my links right now
> - myhdl
> - something like pysystemC
>
> maybe you can find the answer there
>
> cheers,
> Stef- Hide quoted text -
>
> - Show quoted text -

Thanks for the tip.  I checked out myhdl and it has a class called
intbv which does exactly this, and much more than I need.  It's GNU
lesser license though, so not sure how to handle that, if I just want
some concepts of the code as examples, but don't want copy it per se.

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


Re: verilog like class w/ bitslicing & int/long classtype

2009-01-29 Thread Jervis Whitley
On Fri, Jan 30, 2009 at 9:02 AM,  wrote:

> I'm trying to make a script environment with datatypes (or classes)
> for accessing hardware registers.  At the top level, I would like the
> ability to bitwise ops if bit slice brackets are used, but if no
> brackets are used, I would like it to write/read the whole value.
>
> For example, if I have something like:
>
> >>> shadow_register = MyRegClass(0xAA)
> >>> shadow_register
>

is it so bad to type:

>>> shadow_register[:]
170

??
I like this because it is quite clear as to what you are doing, and is
consistent with the
bit slicing you have (already) implemented.

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


Re: slicings: 3 questions

2009-01-29 Thread Alan G Isaac

On 1/29/2009 4:41 PM Robert Kern apparently wrote:

It allows (ab)uses like numpy.mgrid:

 >>> mgrid[0:10:11j]
array([  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])



Ah of course.
Obvious now, but I had presumed some deeper magic in
that syntax, not recognizing that a legitimate slice object
was being created.

Thanks!
Alan

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


Re: Quickbooks

2009-01-29 Thread viglen
On Jan 28, 1:21 pm, Stephen Chapman  wrote:
> Has anyone Implemented the Quickbooks  COM object in Python.  If so can
> you give me
> an Idea of where to begin.
> Thanks

Have you tried to contact the customer support team?
I have used them many times and they are very helpful.
They have different levels of support members to help even the most
complicated questions and problems regarding their POS Software.

1-888-320-7276
QuickBooks: Basic, Pro and Premier and Customer Manager

1-800-348-0254
QuickBooks: Point of Sale

1-866-340-QBES
QuickBooks: Enterprise Solutions

1-800-881-2079
QuickBooks: Simple Start Desktop Edition

Hours of Operation:1
(Pacific time)

Point of Sale:
Mon-Fri 6 A.M. to 8 P.M.
Sat & Sun 7 A.M. to 4 P.M.

All others:
Mon-Fri 6 A.M. to 6 P.M.

Support,
www.AlexandriaComputers.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rounding to the nearest 5

2009-01-29 Thread MRAB

todp...@hotmail.com wrote:

How can you make python round numbers to the nearest 5:
 
Example:
 
3 => 0

8 => 10
23.2 => 20
36 => 35
51.5 => 50
 

Divide by 5, round the result, then multiply by 5.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rounding to the nearest 5

2009-01-29 Thread Tim Chase

How can you make python round numbers to the nearest 5:
 
Example:
 
3 => 0

8 => 10
23.2 => 20
36 => 35
51.5 => 50


I'm not sure *any* rounding system will give those results.  3 
should round up to 5 (not down to 0) and 23.2 should round up to 
25 (not down to 20) in the same way that 8 rounds up to 10.


  tests = (
(3, 5), # not 0
(8, 10),
(23.2, 25), # not 20
(36, 35),
(51.5, 50),
)

  for x, expected in tests:
result = int(round(x / 5.0) * 5)
if result != expected:
  print "Failed:", x, result, expected
  break
  else:
print "All tests passed"


-tkc




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


Re: self-aware list of objects able to sense constituent member alterations?

2009-01-29 Thread Reckoner
On Jan 28, 10:17 pm, Peter  Wang  wrote:
> On Jan 27, 3:16 pm,Reckoner wrote:
>
>
>
> > I'm not sure this is possible, but I would like to have
> > a list of  objects
>
> > A=[a,b,c,d,...,z]
>
> > where,  in the midst of a lot of processing I might do something like,
>
> > A[0].do_something_which_changes_the_properties()
>
> > which alter the properties of the object 'a'.
>
> > The trick is that I would like A to be mysteriously aware that
> > something about the  object 'a' has changed so that when I revisit A,
> > I will know that the other items in the list need to be refreshed to
> > reflect the changes in A as a result of changing 'a'.
>
> > Even better would be to automatically percolate the subsequent changes
> > that resulted from altering 'a' for the rest of the items in the list.
> > Naturally, all of these items are related in some parent-child
> > fashion.
>
> > that might be a lot to ask, however.
>
> > Any advice appreciated.
>
> You should really look at Enthought's Traits package.  It does exactly
> what you are asking for, and much, much more.  See:
>
> http://code.enthought.com/projects/traits/documentation.phphttp://code.enthought.com/projects/traits/examples.php
>
> Using Traits, you could do the following:
>
> from enthought.traits.api import *
> class Child(HasTraits):
>     state = Enum("happy", "sad", "bawling")
>
> class Parent(HasTraits):
>     child = Instance(Child)
>
>     @on_trait_change('child.state')
>     def handler(self):
>         print "new child state:", self.child.state
>
> bob_jr = Child()
> bob = Parent(child = bob_jr)
>
> bob_jr.state = "sad"
> # This would result in bob.handler() being called
>
> (Disclosure: I work at Enthought and have been using Traits heavily
> for the last 4+ years.)
>
> -Peter

I haven't looked at Enthought  in awhile. I want to avoid having to
installing the entire Enthought  toolsuite, however. Would I have to
do that for Traits?

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


Does the Python community really follow the philospy of "Community Matters?"

2009-01-29 Thread r
I been around the list for a while and rubbed sholders with some
pythonistas(some you would not beleieve if i told you) and i just
don't see a community spirit here.

Where are the community projects supporting Python? -- besides the
core devlopment. Seem s that nobody is interested unless their pay-pal
account is involved. I find this all quite disappointing.

Also if anyone dares to mention that Python is a great language or
better in this reguard or that, they get jumped and beat to death by
their "so-called" brothers.

AKAIK there is a group for every languge out there. C, Perl, Java,
Ruby, etc, etc. This is comp.lang.python, if you don't like it, hang
out in "comp.lang.whatever". Don't tell me or anybody "Comparing
Python -> Perl is not allowed here!".






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


Re: ImportError in embedded Python Interpreter

2009-01-29 Thread Gabriel Genellina
En Thu, 29 Jan 2009 17:07:01 -0200,   
escribió:



i have a problem. I compiled Python and the socket module so I got
this structure. (all on windows)

C:\test\dll_files\python25.dll
C:\test\my_app
C:\test\dll_files\DLLs\
C:\test\dll_files\python.exe

If I run python.exe I get the console and I can call "import socket"
which
succeeds. I wrote a small console app which is stored in C:\test\ and
embeddeds the python interpreter. I set the environment variable PATH
so the python25.dll can be load.


The easiest way is to mirror the directory structure of a standard Python  
install. Python looks for Lib/os.py and, once found, derives all the other  
paths from here. See PC/getpathp.c in the source distribution.


You have these alternatives:

- put a lib\* containing at least os.py below the directory containing  
your main executable.


- set a PYTHONHOME variable

- call Py_SetProgramName

- completely replace getpathp.c with your own functions

--
Gabriel Genellina

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


error on building 2.6.1. (_ctypes)

2009-01-29 Thread Bernard Rankin
Hello,

I am trying to build python 2.6 on a machine (web server) that I do not have 
root access to. (has 2.4 installed)

Python 2.5 builds fine, but I am getting an error when I run "make" for 2.6.1. 

Here is the command line I am using:
../configure -prefix=/home/username/local-python/ --enable-unicode=ucs4

(I don't know exactly what the ucs4 thing is for, but all the HOWTOs I saw say 
to use it.  Is it good practice?   Anyway, i get the same error either way.)


Here is what the existing python reports itself as:

Python 2.4.3 (#1, Jul 29 2007, 14:09:31) 
[GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] on linux2




Here is the error after I run "make":

[SNIP]
/home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3941: error: 
syntax error before '*' token
/home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3942: warning: 
function declaration isn't a prototype
/home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c: In function 
`CFuncPtr_nonzero':
/home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3943: error: 
`self' undeclared (first use in this function)

Failed to find the necessary bits to build these modules:
_tkinter   bsddb185   sunaudiodev
To find the necessary bits, look in setup.py in detect_modules() for the 
module's name.


Failed to build these modules:
_ctypes  

running build_script
~~~

I am guessing that I don't need tkinter or sunaudiodev, but what about the 
others?

What's the fix for this sort of thing?  I do see via google some other folks 
are having the same issue, but I could find a solution.

Thanks :)


  

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


Re: slicings: 3 questions

2009-01-29 Thread Gabriel Genellina
En Thu, 29 Jan 2009 19:41:28 -0200, Robert Kern   
escribió:

On 2009-01-29 15:33, Alan G Isaac wrote:

On 1/29/2009 1:37 PM Chris Rebert apparently wrote:



Also, more fundamentally, Python is liberal in what it allows for the
parts of slices, so unifying slices with ranges would break code. For
example, Python is perfectly happy if I go slice("a",[8],object), none
of which are even numbers.


Ah, this is new in Python 3 I take it?


No.


[test using 2.5.1]

Just out of curiosity, I tried with the oldest Python I have:

Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam

slice("a",[8],3j)

slice('a', [8], 3j)

So, no, it's far for being a new feature...

--
Gabriel Genellina

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


Rounding to the nearest 5

2009-01-29 Thread todp...@hotmail.com

How can you make python round numbers to the nearest 5:
 
Example:
 
3 => 0
8 => 10
23.2 => 20
36 => 35
51.5 => 50
 
 
Thanks!
_
Twice the fun—Share photos while you chat with Windows Live Messenger.
http://www.microsoft.com/windows/windowslive/messenger.aspx--
http://mail.python.org/mailman/listinfo/python-list


Re: More mod_wsgi weirdness: process restarts on redirect

2009-01-29 Thread Ron Garret
In article ,
 Joshua Kugler  wrote:

> Ron Garret wrote:
> > My question is: is this supposed to be happening?  Or is this an
> > indication that something is wrong, and if so, what?
> 
> You are probably just hitting a different instance of Apache, thus the
> different process ID.

Yep, that's what it turned out to be.  I thought I had a 
WSGIDaemonProcess processes=1 directive in my config, but I had it in 
the wrong place (a different vhost) so it wasn't actually active.

But that leaves me wondering why the redirect would reliably trigger 
switching processes.  The reason I thought that I had the correct 
configuration and only had one process is that when I reloaded the 
non-redirected page I *always* got the same process ID.  How does 
mod_wsgi decide which process  (and which thread for that matter) to use?

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


Re: verilog like class w/ bitslicing & int/long classtype

2009-01-29 Thread MRAB

John Machin wrote:

On Jan 30, 9:02 am, mark.sea...@gmail.com wrote:

I'm trying to make a script environment with datatypes (or classes)
for accessing hardware registers.  At the top level, I would like the
ability to bitwise ops if bit slice brackets are used, but if no
brackets are used, I would like it to write/read the whole value.

For example, if I have something like:


shadow_register = MyRegClass(0xAA)
shadow_register

170

shadow_register[7:4] = 3  # <== changes value to 0x3A
shadow_register

58

shadow_register = 0x89
shadow_register

137

shadow_register[4:1]

4

I have the bitslice part working.  But of course as expected, if I
type>>> shadow_register

<__main__.boo object at 0x00A130D0>


def __str__(self):
return "d" % self.value


That should be:

return "%d" % self.value

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


Re: Weird invisible arguments issues with Windows

2009-01-29 Thread Gabriel Genellina

En Thu, 29 Jan 2009 19:31:08 -0200, Uberman  escribió:


You all seem to be pointing at the same thing, and on my system, I show:

C:\Users\Administrator>ftype python.file
python.file="D:\Python26\python.exe" "%1" %*

and

C:\Users\Administrator>assoc .py
.py=Python.File

Which all seems to be correct.  I'm guessing this doesn't bode well...


Note that file association is a per-user setting; does it fail using the  
same user as above (Administrator)?


--
Gabriel Genellina

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


Re: parsing text from a file

2009-01-29 Thread MRAB

Wes James wrote:

If I read a windows registry file with a line like this:

"{C15039B5-C47C-47BD-A698-A462F4148F52}"="v2.0|Action=Allow|Active=TRUE|Dir=In|Protocol=6|Profile=Public|App=C:\\Program
Files\\LANDesk\\LDClient\\tmcsvc.exe|Name=LANDesk Targeted
Multicast|Edge=FALSE|"

with this code:

f=open('fwrules.reg2.txt')

for s in f:
  if s.find('LANDesk') <0:
print s,


LANDesk is not found.

Also this does not work:

for s in f:
  try:
i=s.index('L')
print s[i:i+7]
 except:
   pass

all it prints is "LAND"

how do I find LANDesk in a string like this.  is the "\\" messing things up?

How do you know what's in the file? Did you use an editor? It might be 
that the file contents are encoded in, say, UTF-16 and the editor is 
detecting that and decoding it for you, but Python's open() function is 
just returning the contents as a bytestring (Python 2.x).


Try:

import codecs
f = codecs.open('fwrules.reg2.txt', encoding='UTF-16')

for s in f:
if u'LANDesk' in s:
print s,

f.close()
--
http://mail.python.org/mailman/listinfo/python-list


Re: verilog like class w/ bitslicing & int/long classtype

2009-01-29 Thread mark . seagoe
On Jan 29, 3:13 pm, Stef Mientki  wrote:
> mark.sea...@gmail.com wrote:
> > Thanks.  So far these solutions will return strings.  So I can't
> > really treat it like a variable, yet still perform bitslice on it,
> > since I need a special class to do bitslice and bit selection, but as
> > soon as I try to pass it into some other function to check a bit, I
> > gotta then do another operation to convert back to a variable.
>
> > So I can get it to a point where I can do shadow_register[3] and get
> > the value of any bit, or I can do shadow_register[4:2] and get a
> > bitslice, and I can write them just as easily at this point.  If I add
> > the __new__ method into the class, the instance obj becomes int, but
> > is no longer slicable.  I think it looks like I can't have it both
> > ways.
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> there are a few vhdl projects,
> can't find my links right now
> - myhdl
> - something like pysystemC
>
> maybe you can find the answer there
>
> cheers,
> Stef- Hide quoted text -
>
> - Show quoted text -

Thanks, Stef - I'll check them out.  I have a feeling they are going
through a preprocessing stage (ie. won't take command in a pure python
window) but it's worth checking out.
--
http://mail.python.org/mailman/listinfo/python-list


Re: receive and react to MIDI input

2009-01-29 Thread elsjaako
On Jan 30, 12:26 am, elsjaako  wrote:
> On Jan 29, 10:44 pm, elsjaako  wrote:
>
> > On Jan 29, 9:36 pm, r  wrote:
>
> > > On Jan 29, 1:33 pm, elsjaako  wrote:
>
> > > There is a Python MIDI module, i think it is pyMIDI, have you checked
> > > it out?
>
> > Thank you for the responce. Unfortunately, that package is for OS X
> > (it doesn't say that clearly on the website). But it might indeed be
> > worthwhile to mention that I'd be more than happy to use a library, or
> > a finished product (I asked for that elsewhere, nobody had any good
> > ideas)
>
> Never mind. I was wrong. It still doesnt work. Just managed to get a
> normal error instead of WindowsError: exception: access violation
> reading 0x

Finally got it to work! I will soon packige it and publish it
somewhere, so that the next person doesn't have to get frustrated
(hint: use WINCFUNCTYPE)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Get thread pid

2009-01-29 Thread Gabriel Genellina
En Thu, 29 Jan 2009 14:04:49 -0200, Alejandro  
 escribió:



I have Python program running under Linux, that create several
threads, and I want to now the corresponding PID of the threads.

In each of the threads I have

def run(self):
pid = os.getpid()
logger.critical('process ID: %s', pid)

However, the reported PID is the father number, not the PID of the new
thread. Is there a way to get the PID of the thread?


Using "pid" for a thread identifier is confusing; I'd call it tid instead.  
(getpid() used to return a thread id in old Linux kernels, but that was a  
mess).


Try using Thread.ident (requires Python 2.6). I'd expect it to return  
gettid() but I've not checked it; from the docs, it might be a synthesized  
number as well.



In case it doesn't work, you can use ctypes to perform a gettid syscall.

--
Gabriel Genellina

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


Re: More mod_wsgi weirdness: process restarts on redirect

2009-01-29 Thread Ron Garret
In article ,
 Ron Garret  wrote:

> I'm running mod_wsgi under apache (on Debian etch so it's a somewhat out 
> of date version, though I doubt that has anything to do with this issue).
> 
> I have a little test page that displays the process ID under which my 
> app is running, and some global state, so I can tell when the wsgi app 
> gets reloaded.  This mostly only happens when I restart apache, but it 
> also seems to happen when my WSGI app does an HTTP 302 redirect.  (I'm 
> actually using Yaro and calling req.redirect, but that only does a 
> straightforward HTTP 302 redirect as far as I can tell.)  It not only 
> resets the global state, but changes process ID, so it seems to be doing 
> a complete restart of mod_wsgi, which seems a little excessive.
> 
> My question is: is this supposed to be happening?  Or is this an 
> indication that something is wrong, and if so, what?
> 
> Thanks,
> rg

Here's a standalone WSGI app demonstrating the phenomenon:

def redirect_test(env, start):
  if env['PATH_INFO']:
start('302 Found', [('Location', '/')])
return ['Redirecting']
  else:
start('200 OK', [('Content-type', 'text/plain')])
return ['PID', str(os.getpid())]
  pass

application = redirect_test


Fire this up under mod_wsgi and observe that the process ID stays the 
same when you reload the app.  Now add a path component to trigger the 
redirect and observe that process ID changes.

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


Understanding descriptors

2009-01-29 Thread Brian Allen Vanderburg II
I'm trying to better understand descriptors and I've got a few questions 
still after reading some sites.  Here is what I 'think', but please let 
me know if any of this is wrong as I'm sure it probably is.



First when accessing an attribute on a class or instance it must be 
found.  For an instance, it's __dict__ is first search.  If not found 
the class and base class __dict__ are searched.  For a class, the 
__dict__ and base classes __dict__ are search.


If assigning, and the attribute is found and is not a descriptor or if 
the attribute is not found, then the assignment will occur in the 
__dict__ of the class or instance.  If it is found and is a descriptor, 
then __set__ will be call.


For reading, if the attribute is found and is a descriptor, __get__ will 
be called, passing the object (if it is an instance) and class.  If it 
is not a descriptor, the attribute will be returned directly.


Class methods are just functions:

class C(object):
   def F(self):
  pass

C.__dict__['F'] # function object ...

But functions are descriptors:

C.__dict__['F'].__get__ # method wrapper ...

def f1():
   pass

f1.__get__ # method wrapper ...

When a lookup is done it uses this descriptor to make a bound or unbound 
method:


c=C()

C.F # unbound method object, expects explicit instance when calling the 
function
c.F # bound method object provides instance implicitly when calling the 
function


This is also done when adding to the classes:

C.f1 = f1

f1 # function
C.f1 # unbound method
c.f1 # bound method

To prevent this it has to be decorated so the descriptor doesn't cause 
the binding:


C.f2 = staticmethod(f1)
C.f2 # functon
c.f2 # function

Here is a question, why don't instance attributes do the same thing?

c.f3 = f1
c.f3 # function, not bound method

So it is not calling the __get__ method for c.f3  After it finds c.f3 in 
c.__dict__, and since it has a getter, shouldn't it call the __get__ to 
return the bound method.  It is good that it doesn't I know, but I just 
want to know why it doesn't from an implementation view.



Brian Vanderburg II
--
http://mail.python.org/mailman/listinfo/python-list


Re: More mod_wsgi weirdness: process restarts on redirect

2009-01-29 Thread Joshua Kugler
Ron Garret wrote:
> My question is: is this supposed to be happening?  Or is this an
> indication that something is wrong, and if so, what?

You are probably just hitting a different instance of Apache, thus the
different process ID.

j

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


Re: Exec woes

2009-01-29 Thread Rhodri James
On Thu, 29 Jan 2009 08:15:57 -, Hendrik van Rooyen  
 wrote:



 "Rhodri James"  wrote:
To: 
Sent: Thursday, January 29, 2009 6:12 AM
Subject: Re: Exec woes



On Wed, 28 Jan 2009 07:47:00 -, Hendrik van Rooyen
 wrote:



> This is actually not correct - it is the root cause of my trouble.
> if you write, in a nested scope:
>
> exec ( "somestring to execute" in globals(),locals())
>
> You get the syntax error, as the interpreter somehow sees it as one,
> unqualified thing.

Well, no.  Look at the error Python gives you, nested scope or not:

Traceback (most recent call last):
   File "", line 1, in 
TypeError: exec: arg 1 must be a string, file, or code object

If exec is a function, arg 1 is the boolean expression
   "somestring to execute" in globals()
which is unlikely to be what you want.  If exec is a statement,
arg 1 is a tuple of two elements,
   "somestring to execute" in globals()
and
   locals()
which is also unlikely to be what you want.  Neither of these are
giving you a string, file or code object, exactly as the interpreter
is telling you.


Well, no - I stick by my assertion, about the nested scope:


def rubbish():

 def deep_rubbish():
  exec('BUILD = "somestring"' in globals(),locals())

SyntaxError: unqualified exec is not allowed in function 'deep_rubbish'  
it is a

nested function (, line 3)




That is all I was saying - It was the brackets that buggered me,
and adding the globals() and locals() inside the brackets, inside
the nested scope, makes no difference - the interpreter sees it
as an unqualified exec.


Correct.  In the language of the previous error message, the tuple
('BUILD = "something"' in globals(), locals()) is still the first
argument.


Did you actually try it in a nested scope before asserting
"nested scope or not" ?


Sorry, I assumed that you'd noticed that they were complaining
about the same thing.


If you just do, in the outside scope, the thing I did originally:


exec('BUILD = "foobar"')
BUILD

'foobar'




Then the brackets are ignored, and the defaults kick in.


There are no commas, so the brackets are just fulfilling their
usual roll of overriding operator precedence.  Nothing strange
there.

There really is nothing unusual at all going on here.  Please
don't get the idea that brackets do anything unusual with an exec,
or any other Python statement for that matter.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: receive and react to MIDI input

2009-01-29 Thread elsjaako
On Jan 29, 10:44 pm, elsjaako  wrote:
> On Jan 29, 9:36 pm, r  wrote:
>
> > On Jan 29, 1:33 pm, elsjaako  wrote:
>
> > There is a Python MIDI module, i think it is pyMIDI, have you checked
> > it out?
>
> Thank you for the responce. Unfortunately, that package is for OS X
> (it doesn't say that clearly on the website). But it might indeed be
> worthwhile to mention that I'd be more than happy to use a library, or
> a finished product (I asked for that elsewhere, nobody had any good
> ideas)

Never mind. I was wrong. It still doesnt work. Just managed to get a
normal error instead of WindowsError: exception: access violation
reading 0x
--
http://mail.python.org/mailman/listinfo/python-list


Re: verilog like class w/ bitslicing & int/long classtype

2009-01-29 Thread Stef Mientki

mark.sea...@gmail.com wrote:

Thanks.  So far these solutions will return strings.  So I can't
really treat it like a variable, yet still perform bitslice on it,
since I need a special class to do bitslice and bit selection, but as
soon as I try to pass it into some other function to check a bit, I
gotta then do another operation to convert back to a variable.

So I can get it to a point where I can do shadow_register[3] and get
the value of any bit, or I can do shadow_register[4:2] and get a
bitslice, and I can write them just as easily at this point.  If I add
the __new__ method into the class, the instance obj becomes int, but
is no longer slicable.  I think it looks like I can't have it both
ways.
--
http://mail.python.org/mailman/listinfo/python-list
  

try this:

class MyRegClass ( int ) :
 def __init__ ( self, value ) :
   self.Value = value
 def __repr__ ( self ) :
   line = hex ( self.Value )
   line = line [:2] + line [2:].upper()
   return line
 __str__ = __repr__


cheers,
Stef
--
http://mail.python.org/mailman/listinfo/python-list


Re: verilog like class w/ bitslicing & int/long classtype

2009-01-29 Thread Stef Mientki

mark.sea...@gmail.com wrote:

Thanks.  So far these solutions will return strings.  So I can't
really treat it like a variable, yet still perform bitslice on it,
since I need a special class to do bitslice and bit selection, but as
soon as I try to pass it into some other function to check a bit, I
gotta then do another operation to convert back to a variable.

So I can get it to a point where I can do shadow_register[3] and get
the value of any bit, or I can do shadow_register[4:2] and get a
bitslice, and I can write them just as easily at this point.  If I add
the __new__ method into the class, the instance obj becomes int, but
is no longer slicable.  I think it looks like I can't have it both
ways.
--
http://mail.python.org/mailman/listinfo/python-list
  

there are a few vhdl projects,
can't find my links right now
- myhdl
- something like pysystemC

maybe you can find the answer there

cheers,
Stef
--
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe + SQLite problem

2009-01-29 Thread Gabriel Genellina

En Thu, 29 Jan 2009 13:05:11 -0200, Armin  escribió:


I have frozen a running application which is using SQLite with py2exe.
When I start the exe file I see in the log file of the exe:
Traceback (most recent call last):
   File "dpconf.py", line 666, in ?
   File "dpconf.py", line 251, in __init__
   File "sqlite\main.pyc", line 255, in execute
_sqlite.DatabaseError: no such table: genslaveopt

The table exist in the database file ... no problem with the plain  
python version.


Did you solve this problem? As you posted 4 related messages and the last  
one might imply a solution to this first one...


--
Gabriel Genellina

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


Re: verilog like class w/ bitslicing & int/long classtype

2009-01-29 Thread mark . seagoe
Thanks.  So far these solutions will return strings.  So I can't
really treat it like a variable, yet still perform bitslice on it,
since I need a special class to do bitslice and bit selection, but as
soon as I try to pass it into some other function to check a bit, I
gotta then do another operation to convert back to a variable.

So I can get it to a point where I can do shadow_register[3] and get
the value of any bit, or I can do shadow_register[4:2] and get a
bitslice, and I can write them just as easily at this point.  If I add
the __new__ method into the class, the instance obj becomes int, but
is no longer slicable.  I think it looks like I can't have it both
ways.
--
http://mail.python.org/mailman/listinfo/python-list


Re: verilog like class w/ bitslicing & int/long classtype

2009-01-29 Thread John Machin
On Jan 30, 9:55 am, Stef Mientki  wrote:
>   def __repr__ ( self ) :
>     line = hex ( self.Value )
>     line = line [:2] + line [2:].upper()
>     return line
>
> btw, I'm a hardware guy too, and therefor I've never understood why the
> hex function returns lowercase ;-)

0xFF?? *Real* hardware guys prefer FFh or 377 :-)
--
http://mail.python.org/mailman/listinfo/python-list


More mod_wsgi weirdness: process restarts on redirect

2009-01-29 Thread Ron Garret
I'm running mod_wsgi under apache (on Debian etch so it's a somewhat out 
of date version, though I doubt that has anything to do with this issue).

I have a little test page that displays the process ID under which my 
app is running, and some global state, so I can tell when the wsgi app 
gets reloaded.  This mostly only happens when I restart apache, but it 
also seems to happen when my WSGI app does an HTTP 302 redirect.  (I'm 
actually using Yaro and calling req.redirect, but that only does a 
straightforward HTTP 302 redirect as far as I can tell.)  It not only 
resets the global state, but changes process ID, so it seems to be doing 
a complete restart of mod_wsgi, which seems a little excessive.

My question is: is this supposed to be happening?  Or is this an 
indication that something is wrong, and if so, what?

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


Re: Sloooooowwwww WSGI restart

2009-01-29 Thread Ron Garret
In article <498170d4$0$23718$426a7...@news.free.fr>,
 Bruno Desthuilliers  
 wrote:

> Ron Garret a écrit :
> > I'm running a WSGI app under apache/mod_wsgi and I've noticed that 
> > whenever I restart the server after making a code change it takes a very 
> > long time (like a minute) before the script is active again.  In other 
> > words, I do an apachectl restart, reload the page in my browser, and one 
> > minute later it finally comes up.  During this time CPU usage is 
> > essentially zero.  Loading all the code manually into a python 
> > interpreter is virtually instantaneous, and all subsequence interactions 
> > with the app are very fast.
> > 
> > Does anyone have any ideas what might be going on or how to debug this?
> 
> Restarting apache (with or without mod_wsgi) can by itself take some time.
> 
> Now, if you're running mod_wsgi in daemon mode, you _don't_ have to 
> restart apache to reload your code - just touch the wsgi script file and 
> you'll be done, ie with:
> 
> 
>WSGIProcessGroup myproject.tld
>WSGIDaemonProcess myproject.tld user=you group=you
>WSGIReloadMechanism Process
>WSGIScriptAlias / /var/www/myproject/apache/myapp.py
> 
> 
> you just have to touch myapp.py to force reload the subinterpreter(s).

Unfortunately, I'm running Debian Etch, which has an older mod_wsgi, 
which does not have the process reloading mechanism.

But I guess if this gets too painful I'll upgrade.

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


Re: Sloooooowwwww WSGI restart

2009-01-29 Thread Ron Garret
In article <498171a5$0$3681$426a7...@news.free.fr>,
 Bruno Desthuilliers  
 wrote:

> Ron Garret a écrit :
> > In article ,
> >  Aleksandar Radulovic  wrote:
> (snip)
> >> Secondly, why are you restarting apache after code changes? In normal
> >> circumstances, you shouldn't have to do that.
> > 
> > I thought (and experiment confirms) that only the main WSGI app file 
> > gets reloaded automatically when it changes, not the libraries.
> 
> Depends on how you configure mod_wsgi. Read the part about "Process 
> Reloading Mechanism" here:
> http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode

I'm running Debian Etch, which means I have an older version of 
mod_wsgi, which means I don't have the process reloading mechanism.

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


Re: receive and react to MIDI input

2009-01-29 Thread elsjaako
On Jan 29, 8:33 pm, elsjaako  wrote:
> I think this means that the following could be said:
>
> typedef void *HANDLE;
> struct HMIDIIN##__ { int unused; }; typedef struct HMIDIIN##__
> *HMIDIIN;
>
I figured this problem out (I'm sure there will be more...):

A handle should just be a c_void_p ...
--
http://mail.python.org/mailman/listinfo/python-list


Re: verilog like class w/ bitslicing & int/long classtype

2009-01-29 Thread John Machin
On Jan 30, 9:02 am, mark.sea...@gmail.com wrote:
> I'm trying to make a script environment with datatypes (or classes)
> for accessing hardware registers.  At the top level, I would like the
> ability to bitwise ops if bit slice brackets are used, but if no
> brackets are used, I would like it to write/read the whole value.
>
> For example, if I have something like:
>
> >>> shadow_register = MyRegClass(0xAA)
> >>> shadow_register
> 170
> >>> shadow_register[7:4] = 3  # <== changes value to 0x3A
> >>> shadow_register
> 58
> >>> shadow_register = 0x89
> >>> shadow_register
> 137
> >>> shadow_register[4:1]
>
> 4
>
> I have the bitslice part working.  But of course as expected, if I
> type>>> shadow_register
>
> <__main__.boo object at 0x00A130D0>

def __str__(self):
return "d" % self.value
--
http://mail.python.org/mailman/listinfo/python-list


Re: verilog like class w/ bitslicing & int/long classtype

2009-01-29 Thread Stef Mientki

mark.sea...@gmail.com wrote:

I'm trying to make a script environment with datatypes (or classes)
for accessing hardware registers.  At the top level, I would like the
ability to bitwise ops if bit slice brackets are used, but if no
brackets are used, I would like it to write/read the whole value.

For example, if I have something like:

  

shadow_register = MyRegClass(0xAA)
shadow_register


170
  

shadow_register[7:4] = 3  # <== changes value to 0x3A
shadow_register


58
  

shadow_register = 0x89
shadow_register


137
  

shadow_register[4:1]


4

I have the bitslice part working.  But of course as expected, if I
type
  

shadow_register


<__main__.boo object at 0x00A130D0>

I wanted to avoid having something like shadow_register.value just
because it's clumsier.  I read about the __new__() class for
overriding the classtype, like:

print 'foo'
class foo(object):
def __new__(*args): return 0

but if I stick in a __init__(self, val): method, then it chokes saying
val is a global name that's not defined.

Now I know that I have to live with the fact that I can't have
  

shadow_register = 0x89


Because it will get reassigned from my class value to a newly
intialized memory location (int object).  But can I have it read the
value without the .value extension?  Is this even possible?  Maybe
there's a way to override the = operator?  (Go easy on me - I'm a
hardware guy).

  
Interesting what you're doing. I've struggled with the same issues, 
simulating a pic,

never really solved them.
Maybe this is what you're looking for:

class MyRegClass ( object ) :
 def __init__ ( self, value ) :
   self.Value = value
 def __repr__ ( self ) :
   line = hex ( self.Value )
   line = line [:2] + line [2:].upper()
   return line

btw, I'm a hardware guy too, and therefor I've never understood why the 
hex function returns lowercase ;-)


cheers,
Stef

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


Re: parsing text from a file

2009-01-29 Thread Tim Chase

 if s.find('LANDesk') <0:
is True for a line which doesn't contain "LANDesk"; if you want the
opposite, try
 if s.find('LANDesk') >-1:


Or more pythonically, just use

  if 'LANDesk' in s:

-tkc



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


Re: parsing text from a file

2009-01-29 Thread John Machin
On Jan 30, 8:54 am, Wes James  wrote:
> If I read a windows registry file with a line like this:
>
> "{C15039B5-C47C-47BD-A698-A462F4148F52}"="v2.0|Action=Allow|Active=TRUE|Dir=In|Protocol=6|Profile=Public|App=C:\\Program
> Files\\LANDesk\\LDClient\\tmcsvc.exe|Name=LANDesk Targeted
> Multicast|Edge=FALSE|"
>
> with this code:
>
> f=open('fwrules.reg2.txt')
>
> for s in f:
>   if s.find('LANDesk') <0:
>     print s,
>
> LANDesk is not found.

You mean it's not printed. That code prints all lines that don't
contain "LANDesk"

>
> Also this does not work:
>
> for s in f:
>   try:
>     i=s.index('L')
>     print s[i:i+7]
>  except:

Using "except ValueError:" would be safer.

>    pass
>
> all it prints is "LAND"


AFAICT your reported outcome is impossible given that such a line
exists in the file.
>
> how do I find LANDesk in a string like this.

What you were trying (second time, or first time (with >=) should
work. I suggest that to diagnose your problem you change the second
snippet as follows:
1. use except ValueError:
2. print s, len(s), i, and s.find('L') for all lines

>  is the "\\" messing things up?

Each "\\" is presumably just the repr() of a single backslash. In any
case whether there are 0,1,2 or many backslashes in a line or the repr
() thereof has nothing to do with your problem.

HTH,
John
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can't understand what python wants from me

2009-01-29 Thread mark . seagoe
On Jan 29, 1:50 pm, Oleksiy Khilkevich 
wrote:
> Hello, everyone,
> This may be a totally noob question, but since I am one, so here is it.

For the input function, python is expecting you to input a number or a
string.  If you enter 'asd' without the '' then it thinks you are
entering some variable that you've assigned to asd.

Instead of asd, try to enter 'asd'.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can't understand what python wants from me

2009-01-29 Thread Chris Hulan
On Jan 29, 4:50 pm, Oleksiy Khilkevich 
wrote:
> Hello, everyone,
> This may be a totally noob question, but since I am one, so here is it.
>
> I have the following code (not something much 
> of):http://paste.debian.net/27204
> The current code runs well, but the problem is with input 
> value:http://paste.debian.net/27205
> Аs you can see, the numbers are ok, but strings and characters cause
> "not defined" error.
>
> I've obviously missing something important, but tutorial says nothing
> about this.
>
> Thank you for your help.

You want raw_input()

input() expects the string enterd to be Python code, which it evals()
numbers eval to thenmselves

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


Re: Can't understand what python wants from me

2009-01-29 Thread Chris Rebert
On Thu, Jan 29, 2009 at 1:50 PM, Oleksiy Khilkevich
 wrote:
> Hello, everyone,
> This may be a totally noob question, but since I am one, so here is it.
>
> I have the following code (not something much of):
> http://paste.debian.net/27204
> The current code runs well, but the problem is with input value:
> http://paste.debian.net/27205
> Аs you can see, the numbers are ok, but strings and characters cause "not
> defined" error.
>
> I've obviously missing something important, but tutorial says nothing about
> this.

You're using input(). You should be using raw_input(), at least until
everyone switches to Python 3.0 (which confusingly renames raw_input()
to input() because of the exact newbie confusion you're encountering).
raw_input() reads a string from stdin. input() call raw_input() and
then eval()-s the string, hence 'asd' gets interpreted as a variable,
which doesn't exist in your program, hence the error.

For further information, use help() on input and raw_input from the
interactive interpreter REPL.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Can't understand what python wants from me

2009-01-29 Thread Oleksiy Khilkevich

Hello, everyone,
This may be a totally noob question, but since I am one, so here is it.

I have the following code (not something much of): 
http://paste.debian.net/27204
The current code runs well, but the problem is with input value: 
http://paste.debian.net/27205
Аs you can see, the numbers are ok, but strings and characters cause 
"not defined" error.


I've obviously missing something important, but tutorial says nothing 
about this.


Thank you for your help.



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


Re: pygccxml xml output file

2009-01-29 Thread Roman
On Jan 24, 3:25 pm, whatazor  wrote:
> Hi all,
> I start to use this module in order to produce xml( and the make other
> things), but differently from gccxml I don't find the variable that
> set the name of the xml output file after the parsing (in gccxml is -
> fxml), so it creates temporary files.
> how can I do an Is there a tutorial that explain with dectails how it
> works?

I suggest you to ask your questions on the following mailing list:
https://lists.sourceforge.net/lists/listinfo/pygccxml-development

As for your question: see
http://www.language-binding.net/pygccxml/apidocs/pygccxml.parser.project_reader-module.html#create_cached_source_fc
documentation.
and
http://www.language-binding.net/pygccxml/apidocs/pygccxml.parser.project_reader.project_reader_t-class.html#read_files

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


Re: pyAA for Python2.5

2009-01-29 Thread Rob Williscroft
Kottiyath wrote in news:d86a0c1d-e158-4aa1-a47f-e2149948bdc3
@p2g2000prf.googlegroups.com in comp.lang.python:

> On Jan 29, 1:51 am, Rob Williscroft  wrote:
>> Kottiyath wrote in news:6a594643-f6a2-4d8d-aab3-27eb16cb2fb8
>> @b38g2000prf.googlegroups.com in comp.lang.python:

>>
>> > I have mingw32-gcc in my path. If I try that too -it fails.
>>
>> > C:\Documents and Settings\Guest\pyAA>python setup.py install -c
>> > "mingw32-gcc"
>> > invalid command name 'mingw32-gcc'
>>
>> All the examples I found via google have the tool name as "mingw32"
>> so try:
>>
>>         python setup.py install -c mingw32

> Thank you Rob.
> The installation went ahead for some more time - but failed showing a
> lot of errors:
>>compile
> running build
> running build_py
> file pyAAc.py (for module pyAAc) not found
> file pyAAc.py (for module pyAAc) not found
> ...
> pyAAc.cpp:5887: error: `EVENT_OBJECT_HELPCHANGE' was not declared in
> this scope
> pyAAc.cpp:5888: error: `EVENT_OBJECT_DEFACTIONCHANGE' was not declared
> in this scope
> pyAAc.cpp:5889: error: `EVENT_OBJECT_ACCELERATORCHANGE' was not
> declared in this scope
> ...
> error: command 'gcc' failed with exit status 1
> 
> I cannot understand why it fails. I have not worked in C till now, so
> I am pretty confused.
> I googled also, but to no avail.
> 

Looks like the package needs some headers that haven't yet been 
ported to to MinGW.

Alas that meands you'll need to build with the Microsoft SDK 
and compiler.

You can get the SDK including a non-optimising compiler from:

http://www.microsoft.com/downloads/details.aspx?FamilyId=9B3A2CA6-3647-
4070-9F41-A333C6B9181D&displaylang=en

or maybe here:

http://www.microsoft.com/downloads/details.aspx?FamilyId=0BAF2B35-C656-
4969-ACE8-E4C0C0716ADB&displaylang=en

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: parsing text from a file

2009-01-29 Thread Vlastimil Brom
2009/1/29 Wes James :
> If I read a windows registry file with a line like this:
>
...
>
> with this code:
>
> f=open('fwrules.reg2.txt')
>
> for s in f:
>  if s.find('LANDesk') <0:
>print s,
>
>
> LANDesk is not found.
>
> how do I find LANDesk in a string like this.  is the "\\" messing things up?
...
>
> thx,
>
> -wj
>
Hi,
 if s.find('LANDesk') <0:
is True for a line which doesn't contain "LANDesk"; if you want the
opposite, try
 if s.find('LANDesk') >-1:
hth
  vbr
--
http://mail.python.org/mailman/listinfo/python-list


Re: is python Object oriented??

2009-01-29 Thread Ben Finney
MC  writes:

> Hi!
> 
> Il se trouve que Chris Rebert a formulé :
> > Python has functions, which are not associated with a class
> 
> functions are methods of builtin...

No, because ‘builtin’ is not a class.

-- 
 \  “The shortest distance between two points is under |
  `\  construction.” —Noelie Alito |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


verilog like class w/ bitslicing & int/long classtype

2009-01-29 Thread mark . seagoe
I'm trying to make a script environment with datatypes (or classes)
for accessing hardware registers.  At the top level, I would like the
ability to bitwise ops if bit slice brackets are used, but if no
brackets are used, I would like it to write/read the whole value.

For example, if I have something like:

>>> shadow_register = MyRegClass(0xAA)
>>> shadow_register
170
>>> shadow_register[7:4] = 3  # <== changes value to 0x3A
>>> shadow_register
58
>>> shadow_register = 0x89
>>> shadow_register
137
>>> shadow_register[4:1]
4

I have the bitslice part working.  But of course as expected, if I
type
>>> shadow_register
<__main__.boo object at 0x00A130D0>

I wanted to avoid having something like shadow_register.value just
because it's clumsier.  I read about the __new__() class for
overriding the classtype, like:

print 'foo'
class foo(object):
def __new__(*args): return 0

but if I stick in a __init__(self, val): method, then it chokes saying
val is a global name that's not defined.

Now I know that I have to live with the fact that I can't have
>>> shadow_register = 0x89
Because it will get reassigned from my class value to a newly
intialized memory location (int object).  But can I have it read the
value without the .value extension?  Is this even possible?  Maybe
there's a way to override the = operator?  (Go easy on me - I'm a
hardware guy).

Thx,
Mark



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


Re: UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 10442: character maps to

2009-01-29 Thread Benjamin Kaplan
On Thu, Jan 29, 2009 at 4:19 PM, John Machin  wrote:

> Benjamin Kaplan  case.edu> writes:
>
> >
> >
> > On Thu, Jan 29, 2009 at 12:09 PM, Anjanesh Lekshminarayanan 
> anjanesh.net> wrote:
> > > It does auto-detect it as cp1252- look at the files in the traceback
> and
> > > you'll see lib\encodings\cp1252.py. Since cp1252 seems to be the wrong
> > > encoding, try opening it as utf-8 or latin1 and see if that fixes it.
>
> Benjamin, "auto-detect" has strong connotations of the open() call (with
> mode
> including text and encoding not specified) reading some/all of the file and
> trying to guess what the encoding might be -- a futile pursuit and not what
> the
> docs say:
>
> """encoding is the name of the encoding used to decode or encode the file.
> This
> should only be used in text mode. The default encoding is platform
> dependent,
> but any encoding supported by Python can be passed. See the codecs module
> for
> the list of supported encodings"""
>
> On my machine [Windows XL SP3] sys.getdefaultencoding() returns 'utf-8'. It
> would be interesting to know
> (1) what is produced on Anjanesh's machine
> (2) how the default encoding is derived (I would have thought I was a prime
> candidate for 'cp1252')
> (3) whether the 'default encoding' of open() is actually the same as the
> 'default encoding' of sys.getdefaultencoding() -- one would hope so but the
> docs
> don't say so.


First of all, you're right that might be confusing. I was thinking of
auto-detect as in "check the platform and locale and guess what they usually
use". I wasn't thinking of it like the web browsers use it.

I think it uses locale.getpreferredencoding(). On my machine, I get
sys.getpreferredencoding() == 'utf-8' and locale.getdefaultencoding()==
'cp1252'. When I open a file without specifying the encoding, it's cp1252.


>
> > Thanks a lot ! utf-8 and latin1 were accepted !
>
> Benjamin and Anjanesh, Please understand that
> any_random_rubbish.decode('latin1') will be "accepted". This is *not*
> useful
> information to be greeted with thanks and exclamation marks. It is merely a
> by-product of the fact that *any* single-byte character set like latin1
> that
> uses all 256 possible bytes can not fail, by definition; no character "maps
> to
> ".


If you check my response to Anjanesh's comment, I mentioned that he should
either find out which encoding it is in particular or he should open the
file in binary mode. I suggested utf-8 and latin1 because those are the most
likely candidates for his file since cp1252 was already excluded. Looking at
a character map, 0x9d is a control character in latin1, so the page is
probably UTF-8 encoded. Thinking about it now, it could also be MacRoman but
that isn't as common as UTF-8.

>
> > If you want to read the file as text, find out which encoding it actually
> is.
> In one of those encodings, you'll probably see some nonsense characters. If
> you
> are just looking at the file as a sequence of bytes, open the file in
> binary
> mode rather than text. That way, you'll avoid this issue all together (just
> make
> sure you use byte strings instead of unicode strings).
>
> In fact, inspection of Anjanesh's report:
> """UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position
> 10442: character maps to 
> The string at position 10442 is something like this :
> "query":"0 1»Ý \u2021 0\u201a0 \u2021»Ý"," """
>
> draws two observations:
> (1) there is nothing in the reported string that can be unambiguously
> identified
> as corresponding to "0x9d"
> (2) it looks like a small snippet from a Python source file!
>
> Anjanesh, Is it a .py file? If so, is there something like "# encoding:
> cp1252"
> or "# encoding: utf-8" near the start of the file? *Please* tell us what
> sys.getdefaultencoding() returns on your machine.
>
> Instead of "something like", please report exactly what is there:
>
> print(ascii(open('the_file', 'rb').read()[10442-20:10442+21]))
>
> Cheers,
> John
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't eval of generator expression work with locals?

2009-01-29 Thread Gabriel Genellina
En Wed, 28 Jan 2009 18:06:01 -0200, Peter Otten <__pete...@web.de>  
escribió:

Gabriel Genellina wrote:


(I think this has to do with free variables in the "right side" (after
the "in" keyword) of a generator expression; they appear to be evaluated
when the expression is *defined*, not when is is *used*. By contrast,  
free
variables in the "left side" appear to be evaluated when the expression  
is

used.)


Indeed, the right side is evaluated in the enclosing namespace and then
passed as an argument to the genexpr:

 >>> dis.dis(compile("(x for y in z)", "nofile", "exec"))
  1   0 LOAD_CONST   0 ( at
0x2b22b2dcf828, file "nofile", line 1>)
  3 MAKE_FUNCTION0
  6 LOAD_NAME0 (z)
  9 GET_ITER
 10 CALL_FUNCTION1
 13 POP_TOP
 14 LOAD_CONST   1 (None)
 17 RETURN_VALUE


Yes, this is explained (in not so much detail) in the Language Reference.  
Now I *know* how it works, but still isn't *obvious* to me.


--
Gabriel Genellina

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


  1   2   >