Re: [Tutor] Filling orders FIFO

2011-07-16 Thread Izz ad-Din Ruhulessin
Why are you doing it at the low level? Have you consideren using a framework
like Django for example?

2011/7/16 Steven D'Aprano 

> Charles John wrote:
>
>> Hi I am new to python and was wondering what the best way to create an
>> order(bid and offer) queue, then match a bid and offer so that if
>> bid==offer, creates a filled order FIFO in python cgi using mysql? Does
>> anybody have any ideas? It would be greatly appreciated.
>>
>
> The simplest way to use a queue is with a list:
>
> queue = []
>
> You push items onto the queue with queue.append(item) and pop them off with
> queue.pop(0).
>
> However, popping items may be slow if the queue grows very large (tens of
> thousands of items). It might be better to use a deque (double ended queue)
> instead of a list:
>
> from collections import deque
> queue = deque()
>
> To push items onto the right hand side of the queue, then pop them off the
> left hand side:
>
> queue.append(item)
> queue.popleft()
>
>
> As for the rest of your question, I don't understand what you mean by an
> order(bid and offer) queue. Perhaps you could give an example of what you
> mean.
>
>
> --
> Steven
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hello World in Python without space

2011-07-10 Thread Izz ad-Din Ruhulessin
Sending args to the print command always puts spaces between them.

Try:
print("Hello {name}!".format(name=name))





2011/7/10 Robert H 

>  Dear all,
>
>
> I have Python 3.2 installed on Windows 7. I am a complete beginner playing
> around with the basic functions. My problem is the following script:
>
>
> name="world"
> print("Hello", name,"!")
>
>
> The result is:
> Hello world !
>
>
> However, I don't want the space before the exclamation mark. I want this:
> Hello world!
>
>
> I tried to solve the problem with e.g.:
> print("Hello",name.strip(),"!")
> but the result is the same.
>
>
> Can anyone out there help me? Thank you.
>
>
> Regards,
> Robert
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Limit raw_input to hundredth decimal point

2011-07-01 Thread Izz ad-Din Ruhulessin
You can use a regular expression or plain simple len()

2011/7/1 Ryan Kirk 

> Is there a way to limit raw_input to the hundredth decimal point?
>
> For example, I'd like to allow the user to enter 5.75 but not 5.756:
>
> dollars = raw_input("Please enter a dollar amount: $")
>
> Thanks!
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Objects C++ vs Python

2011-06-09 Thread Izz ad-Din Ruhulessin
Compared to Python, I do not even consider C++ an object oriënted language.

2011/6/9 Ashwini Oruganti 

> On Thu, Jun 9, 2011 at 2:18 PM, Alan Gauld wrote:
>
> C++ grew out of C so it has a lot of non OOP features. It is no
>> surprise to find therefore that its primitive types are related to
>> memory allocation and raw data rather than objects.
>>
>
>
>
>> No object is standard in OOP. It is a concept. It is the instantiated
>> encapsulation of data and function. How it is created varies between
>> language implementations.
>>
>
>
> Well, that clears it up!  I guess Python is a wider implementation of OOP,
> hence a wider use of objects. Thanks a lot.
>
>
>
>
> On Thu, Jun 9, 2011 at 3:32 PM, Walter Prins  wrote:
>
> Object Oriented code in e.g. a procedural language like C, which obviously
>> doesn't support the notion of objects explicitly in the language, although
>> then it's up to you to come up with conventions and infrastructure to
>> support the concept of object orientation in your program.
>
>
>
> Didn't know that!  It's interesting that  GObject is itself written in C,
> which is a procedural laguage..
>
>
>
>
> --
> Regards,
> Ashwini
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help wrapping my head around duck typing

2011-05-24 Thread Izz ad-Din Ruhulessin
I forgot to mention
strptime<http://docs.python.org/library/datetime.html#strftime-strptime-behavior>

2011/5/25 Izz ad-Din Ruhulessin 

> Hi Cory,
>
> From your description it seems to me that your case is more one of
> asserting that your function received valid arguments, than a matter of
> static-vs-ducktyping. Even with type checking, they can still generate
> errors (out of bounds, incorrect formatting).
>
> Now i've seen some discussions where people stated that type checking and
> argument assertion are bad and that the programmer should just let the code
> run until it bumps into and error. Python programmers are very inclined to
> "forgiveness is easier than permission", also referred to in the article you
> mentioned. However, the principle is only valid in cases where it is
> guaranteed that an incorrect type or value will produce and exception. For
> example, if you are interfacing between C and Python this can often not be
> the case -- or it will crash your programme without any kind of traceback
> (the dreaded segfault)
>
> Will an incorrect type or value raise an exception in your proposed
> solutions? It probably will, so it is probably best to go for
> try-except-finally clauses.
>
> A sidenote: personnally I would glob the directory and then sort the list
> by file creation date.
>
> Kind regards,
>
> Izz ad-Din Ruhulessin
>
> 2011/5/24 Cory Teshera-Sterne 
>
>> Hi folks,
>>
>> Coming from a language background that has a different approach to
>> variables (*cough* Java *cough*), I'm trying to understand Python's typing
>> conventions and how to deal with unknown variable types in my code. And as a
>> newbie, I'm really concerned with not writing code that will make the actual
>> Python programmer who will be maintaining my code jump out the window from
>> frustration.
>>
>> An example: I have a directory tree containing year directories (in the
>> form , ie, "2011"), which contain month directories (in the form MM, ie,
>> "05"), which in turn contain files. I'm writing a Python function to iterate
>> over the tree & return a list of the file names from either the full tree
>> (args==None) or a specified time period within that - ie, Feb. '10 to May
>> '11 (args==startdate, enddate). I'm not sure what the most pythonic approach
>> to dealing with the variables here would be. I have several options:
>>  - accept datetime objects and then get the year/month info from that
>>  - accept a string (and maybe check its length, add "20" if it's two
>> digits, or reject it if it's more than 4)
>>  - accept an integer (and maybe check that it's reasonable)
>>
>> My first inclination would be to only accept 4-digit year and 2-digit
>> month integers and fail the rest, but I understand the value of dealing with
>> different input types here. My second guess would be to use isinstance() for
>> each possibility, since different things need to happen in each case. The
>> "pythonic" approach, as best as I can gather, would be a try/catch block and
>> use the exception types to do the different processing. However, for
>> example, both trying to get a year from a string and a len() of an int raise
>> a TypeError, and in general I'm not sure how to approach this - or am I
>> overthinking things?
>>
>> Finally, I'm aware that I'm really bringing up two topics here:
>>
>> 1) What is the best approach in this and similar cases, in terms of
>> actual, working code that won't make the next user of this code cry? How
>> do/should I distinguish error types in this case?, and less importantly,
>>
>> 2) Can anyone help me get a good handle on the philosophical issues here?
>> I've read several discussions (both strongly against 
>> type-checking<http://www.canonical.org/%7Ekragen/isinstance/>and more
>> lenient<http://dobesland.wordpress.com/2007/10/07/python-isinstance-considered-useful/>,
>> as well as good general 
>> explanations<http://www.voidspace.org.uk/python/articles/duck_typing.shtml>),
>> but some of it's over my head, a lot of it says something like "I suggest we
>> change Python so it does X", and I'm not sure what it all means for me and
>> my little filename-grabbing script. It's all just a bunch of quaking to me
>> right now ...
>>
>> Thanks so much,
>> Cory
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help wrapping my head around duck typing

2011-05-24 Thread Izz ad-Din Ruhulessin
Hi Cory,

>From your description it seems to me that your case is more one of asserting
that your function received valid arguments, than a matter of
static-vs-ducktyping. Even with type checking, they can still generate
errors (out of bounds, incorrect formatting).

Now i've seen some discussions where people stated that type checking and
argument assertion are bad and that the programmer should just let the code
run until it bumps into and error. Python programmers are very inclined to
"forgiveness is easier than permission", also referred to in the article you
mentioned. However, the principle is only valid in cases where it is
guaranteed that an incorrect type or value will produce and exception. For
example, if you are interfacing between C and Python this can often not be
the case -- or it will crash your programme without any kind of traceback
(the dreaded segfault)

Will an incorrect type or value raise an exception in your proposed
solutions? It probably will, so it is probably best to go for
try-except-finally clauses.

A sidenote: personnally I would glob the directory and then sort the list by
file creation date.

Kind regards,

Izz ad-Din Ruhulessin

2011/5/24 Cory Teshera-Sterne 

> Hi folks,
>
> Coming from a language background that has a different approach to
> variables (*cough* Java *cough*), I'm trying to understand Python's typing
> conventions and how to deal with unknown variable types in my code. And as a
> newbie, I'm really concerned with not writing code that will make the actual
> Python programmer who will be maintaining my code jump out the window from
> frustration.
>
> An example: I have a directory tree containing year directories (in the
> form , ie, "2011"), which contain month directories (in the form MM, ie,
> "05"), which in turn contain files. I'm writing a Python function to iterate
> over the tree & return a list of the file names from either the full tree
> (args==None) or a specified time period within that - ie, Feb. '10 to May
> '11 (args==startdate, enddate). I'm not sure what the most pythonic approach
> to dealing with the variables here would be. I have several options:
>  - accept datetime objects and then get the year/month info from that
>  - accept a string (and maybe check its length, add "20" if it's two
> digits, or reject it if it's more than 4)
>  - accept an integer (and maybe check that it's reasonable)
>
> My first inclination would be to only accept 4-digit year and 2-digit month
> integers and fail the rest, but I understand the value of dealing with
> different input types here. My second guess would be to use isinstance() for
> each possibility, since different things need to happen in each case. The
> "pythonic" approach, as best as I can gather, would be a try/catch block and
> use the exception types to do the different processing. However, for
> example, both trying to get a year from a string and a len() of an int raise
> a TypeError, and in general I'm not sure how to approach this - or am I
> overthinking things?
>
> Finally, I'm aware that I'm really bringing up two topics here:
>
> 1) What is the best approach in this and similar cases, in terms of actual,
> working code that won't make the next user of this code cry? How do/should I
> distinguish error types in this case?, and less importantly,
>
> 2) Can anyone help me get a good handle on the philosophical issues here?
> I've read several discussions (both strongly against 
> type-checking<http://www.canonical.org/%7Ekragen/isinstance/>and more
> lenient<http://dobesland.wordpress.com/2007/10/07/python-isinstance-considered-useful/>,
> as well as good general 
> explanations<http://www.voidspace.org.uk/python/articles/duck_typing.shtml>),
> but some of it's over my head, a lot of it says something like "I suggest we
> change Python so it does X", and I'm not sure what it all means for me and
> my little filename-grabbing script. It's all just a bunch of quaking to me
> right now ...
>
> Thanks so much,
> Cory
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cpython

2011-05-12 Thread Izz ad-Din Ruhulessin
Hi,

CPython is the C implementation of Python. You can read the tutorial in the
Python docs.

It is a rather advanced topic, however. If you nevertheless want to delve
into it, it might be a good idea to check out www.cython.org first.

2011/5/12 tee chwee liong 

>  hi all,
>
> i just started python but i'm hearing there is cpython. what is it
> different from python? is there any tutorials i can refer.
>
> thanks
> tcl
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Shared web host and setting the python environment...

2011-03-05 Thread Izz ad-Din Ruhulessin
Hi,

I would go for appending sys.path. This is a simple way to do it, and
perhaps not even needed for each python file (only files which use the
modules that you have installed))

Another way to do it is adding the modules you need to sys.modules manually.

2011/3/5 Modulok 

> List,
>
> Background:
> I'm on a linux based shared web host. They cater to PHP, not python.
> (There's no third party python modules even installed!) So I installed
> a virtual python in my home directory, plus easy_install and a bunch
> of modules. Great!
>
> The Problem:
> Unfortunately, the web server uses the system python, not my virtual
> python, or my modules. (It does execute my scripts as my uid though.)
> I need modify the environment of every one of my python scripts,
> perhaps appending to sys.path, so that my third party modules in my
> home directory can be found. I have zero control over the web server
> process or its environment.
>
> Possible Solutions I thought of:
> One way to do this would be to edit 'sys.path' at the top of every
> python script. (Sounds ugly.) Another would be to import the 'user'
> module and go that route. (Fine, but it's depricated. What replaces
> it?) A third idea would be to re-direct all requests via mod_rewrite
> to a single python file or shell script, which sets the environment
> and calls my python scripts as a sub-process. (Slow, which is fine,
> but some security concerns here.)
>
> Given my situation, what's the best way to accomplish this? (Aside
> from a new hosting company or a virtual private server.)
>
> Any suggestions appreciated. Thanks!
> -Modulok-
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A class that instantiates conditionally ?

2011-03-02 Thread Izz ad-Din Ruhulessin
Of course that would be:

> foo = lambda condition: MyClass() if condition else None


2011/3/3 Izz ad-Din Ruhulessin 

> Maybe:
>
> foo = lambda x: MyClass() if condition else None
>
>
> 2011/3/3 David 
>
> Another classic case of trying something not the best way, due to
>>  inexperience.
>> But it has been a good process: I learned something new from
>> setting myself the initial puzzle and then finding a solution,and then
>> learned more from the great tutoring here. Thanks very much for all
>> the replies.
>>
>> On 2 March 2011 03:31, Alan Gauld  wrote:
>> >
>> >> class MyClass_2(object):
>> >>def __new__(self, condition):
>> >> if condition:
>> >>   return object.__new__(self)
>> >> else:
>> >>   return None
>> >
>> > Thats pretty much how I'd do it.
>>
>> Thanks for reviewing my code.
>>
>> On 2 March 2011 03:35, Alan Gauld  wrote:
>> >
>> > Oops, sent too soon.
>> >
>> > I meant to add that you should realize that the implication of your
>> > design is that the user of the class now has to check each object
>> > to see if it is a valid reference or None. You could raise an exception
>> > instead of returning None which allows a try/except style...
>> >
>> > This extra overhead is one reason these kinds of "clever" tricks
>> > are usually avoided. A valid object with null content is often
>> > preferrable, or a singleton style pattern. But occasionally your
>> > style is needed, just be aware of the extra overhead you
>> > introduce by using it.
>>
>> Spot on. It would require two "if" tests, one inside __new__() and
>> another in the code.
>>
>> I found your mention of try/except there especially helpful, because
>> it was a pertinent reminder that I was not thinking in "ask forgiveness
>> not permission" mode. This (newbie mistake) occurred because I
>> wanted my application to continue, not abort with an exception, but
>> after your prompt I recalled that "except" doesn't have to raise
>> exceptions
>> it can do other things.
>>
>> So I went in the direction you suggested and I am happy with the results.
>> Basically my application is interpreting binary file data by instantiating
>> a
>> structured object for each file in a fixed list of binary files, and I
>> was looking
>> for a neat way to ignore any errors on files that might not be present
>> (failed to open). So, after feedback here my solution now is to use
>> try/except in the class __init__() to create a valid object with null
>> content,
>> and then use "if" tests in the rest of the code that processes the objects
>> to
>> just ignore them if they are null, which is a nice clear way to do it.
>>
>> On 2 March 2011 20:44, Steven D'Aprano  wrote:
>> >
>> > By convention, the name of the first argument to __new__ is cls, not
>> self,
>> > because it is bound to the class object itself (MyClass_2 in this
>> example)
>> > rather than the instance. The instance doesn't yet exist, so that's not
>> > surprising!
>>
>> Thanks for pointing that out. In 2.6 Language Reference 3.4.3 they used
>> "mcs" (metaclass?) which I didn't comprehend at all at the time (the
>> mindset
>> of just wanting to get some code working to fix a problem is not the most
>> helpful mindset for decoding a large body of new information), so I just
>> used
>> "self" when getting their example code to work for me. In Section 3.4.1
>> they
>> use "cls" which I now see clearly and understand thanks.
>>
>> On 3 March 2011 03:03, Knacktus  wrote:
>> >
>> > I think that's too clever ;-).
>>
>> I agree now .. but it was a useful experiment. Thanks for the tute.
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A class that instantiates conditionally ?

2011-03-02 Thread Izz ad-Din Ruhulessin
Maybe:

foo = lambda x: MyClass() if condition else None


2011/3/3 David 

> Another classic case of trying something not the best way, due to
>  inexperience.
> But it has been a good process: I learned something new from
> setting myself the initial puzzle and then finding a solution,and then
> learned more from the great tutoring here. Thanks very much for all
> the replies.
>
> On 2 March 2011 03:31, Alan Gauld  wrote:
> >
> >> class MyClass_2(object):
> >>def __new__(self, condition):
> >> if condition:
> >>   return object.__new__(self)
> >> else:
> >>   return None
> >
> > Thats pretty much how I'd do it.
>
> Thanks for reviewing my code.
>
> On 2 March 2011 03:35, Alan Gauld  wrote:
> >
> > Oops, sent too soon.
> >
> > I meant to add that you should realize that the implication of your
> > design is that the user of the class now has to check each object
> > to see if it is a valid reference or None. You could raise an exception
> > instead of returning None which allows a try/except style...
> >
> > This extra overhead is one reason these kinds of "clever" tricks
> > are usually avoided. A valid object with null content is often
> > preferrable, or a singleton style pattern. But occasionally your
> > style is needed, just be aware of the extra overhead you
> > introduce by using it.
>
> Spot on. It would require two "if" tests, one inside __new__() and
> another in the code.
>
> I found your mention of try/except there especially helpful, because
> it was a pertinent reminder that I was not thinking in "ask forgiveness
> not permission" mode. This (newbie mistake) occurred because I
> wanted my application to continue, not abort with an exception, but
> after your prompt I recalled that "except" doesn't have to raise exceptions
> it can do other things.
>
> So I went in the direction you suggested and I am happy with the results.
> Basically my application is interpreting binary file data by instantiating
> a
> structured object for each file in a fixed list of binary files, and I
> was looking
> for a neat way to ignore any errors on files that might not be present
> (failed to open). So, after feedback here my solution now is to use
> try/except in the class __init__() to create a valid object with null
> content,
> and then use "if" tests in the rest of the code that processes the objects
> to
> just ignore them if they are null, which is a nice clear way to do it.
>
> On 2 March 2011 20:44, Steven D'Aprano  wrote:
> >
> > By convention, the name of the first argument to __new__ is cls, not
> self,
> > because it is bound to the class object itself (MyClass_2 in this
> example)
> > rather than the instance. The instance doesn't yet exist, so that's not
> > surprising!
>
> Thanks for pointing that out. In 2.6 Language Reference 3.4.3 they used
> "mcs" (metaclass?) which I didn't comprehend at all at the time (the
> mindset
> of just wanting to get some code working to fix a problem is not the most
> helpful mindset for decoding a large body of new information), so I just
> used
> "self" when getting their example code to work for me. In Section 3.4.1
> they
> use "cls" which I now see clearly and understand thanks.
>
> On 3 March 2011 03:03, Knacktus  wrote:
> >
> > I think that's too clever ;-).
>
> I agree now .. but it was a useful experiment. Thanks for the tute.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multiples python files

2011-02-28 Thread Izz ad-Din Ruhulessin
You can only call methods on a class without instantiating it, if it are
classmethods.

http://pyref.infogami.com/classmethod

2011/2/28 Christopher Brookes 

> I don't understand
>
> @classmethod
> def DisplayAll(cls, herosAll
> ):
>
> What is cls ?
>
> 2011/2/28 Izz ad-Din Ruhulessin 
>
>> @classmethod
>> def DisplayAll(herosAll):
>>
>> is of course:
>>
>> @classmethod
>> def DisplayAll(cls, herosAll):
>>
>> 2011/2/28 Izz ad-Din Ruhulessin 
>>
>> Hi, you must pass the herosAll list to the DisplayAll() method like this
>>>
>>> class Character():
>>> @classmethod
>>> def DisplayAll(herosAll):
>>>  print ('There is', Character.CharacterCount, 'heros')
>>> for heros in herosAll:
>>> heros.DisplayCharacterInfos()
>>>
>>> herosAll = [
>>>  Character(1,"Antaa","Soldat moins fort",15,5,8),
>>>  Character(2,"Klaitos","Soldat moins fort",15,5,8)]
>>>
>>> Character.DisplayAll(herosAll)
>>>
>>>
>>> 2011/2/28 Christopher Brookes 
>>>
>>>>  Hi, first sorry for my poor english, i'm a french guy, i'm trying to
>>>> make the best :(
>>>>
>>>> I would like to split my python script into multiples files.
>>>> I want :
>>>> A file which contains only class creations and methods,
>>>> A file with some personals functions
>>>> And a main.py which is the main script.
>>>>
>>>> But i'm getting some problems
>>>> In class creation file, i've a init method which create a character  (it
>>>> works).
>>>> They are created in main.py like this :
>>>>
>>>> herosAll = [
>>>>  Character(1,"Antaa","Soldat moins fort",15,5,8),
>>>>  Character(2,"Klaitos","Soldat moins fort",15,5,8)]
>>>>
>>>> But when i want to display all information about my character with :
>>>>
>>>> class Character():
>>>> def DisplayAll():
>>>> print ('There is', Character.CharacterCount, 'heros')
>>>> for heros in herosAll:
>>>> heros.DisplayCharacterInfos()
>>>>
>>>> I'm getting :
>>>>
>>>> Traceback (most recent call last):
>>>>   File "main.py", line 28, in 
>>>> Character.DisplayAll()
>>>>   File "/home/christopher/class_creation.py", line 53, in DisplayAll
>>>> for heros in herosAll:
>>>> NameError: global name 'herosAll' is not defined
>>>>
>>>> I know the source of the problem. The list herosAll is declared in
>>>> main.py so he can't access to it. But i'm stuck here. How can he get it ?
>>>> Have I to append the list in the init method ?
>>>>
>>>> Thank you for ready.
>>>>
>>>>
>>>>
>>>> --
>>>> Brookes Christopher.
>>>>
>>>> ___
>>>> Tutor maillist  -  Tutor@python.org
>>>> To unsubscribe or change subscription options:
>>>> http://mail.python.org/mailman/listinfo/tutor
>>>>
>>>>
>>>
>>
>
>
> --
> Brookes Christopher.
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multiples python files

2011-02-28 Thread Izz ad-Din Ruhulessin
@classmethod
def DisplayAll(herosAll):

is of course:

@classmethod
def DisplayAll(cls, herosAll):

2011/2/28 Izz ad-Din Ruhulessin 

> Hi, you must pass the herosAll list to the DisplayAll() method like this
>
> class Character():
> @classmethod
> def DisplayAll(herosAll):
> print ('There is', Character.CharacterCount, 'heros')
> for heros in herosAll:
> heros.DisplayCharacterInfos()
>
> herosAll = [
>  Character(1,"Antaa","Soldat moins fort",15,5,8),
>  Character(2,"Klaitos","Soldat moins fort",15,5,8)]
>
> Character.DisplayAll(herosAll)
>
>
> 2011/2/28 Christopher Brookes 
>
>> Hi, first sorry for my poor english, i'm a french guy, i'm trying to make
>> the best :(
>>
>> I would like to split my python script into multiples files.
>> I want :
>> A file which contains only class creations and methods,
>> A file with some personals functions
>> And a main.py which is the main script.
>>
>> But i'm getting some problems
>> In class creation file, i've a init method which create a character  (it
>> works).
>> They are created in main.py like this :
>>
>> herosAll = [
>>  Character(1,"Antaa","Soldat moins fort",15,5,8),
>>  Character(2,"Klaitos","Soldat moins fort",15,5,8)]
>>
>> But when i want to display all information about my character with :
>>
>> class Character():
>> def DisplayAll():
>> print ('There is', Character.CharacterCount, 'heros')
>> for heros in herosAll:
>> heros.DisplayCharacterInfos()
>>
>> I'm getting :
>>
>> Traceback (most recent call last):
>>   File "main.py", line 28, in 
>> Character.DisplayAll()
>>   File "/home/christopher/class_creation.py", line 53, in DisplayAll
>> for heros in herosAll:
>> NameError: global name 'herosAll' is not defined
>>
>> I know the source of the problem. The list herosAll is declared in main.py
>> so he can't access to it. But i'm stuck here. How can he get it ?
>> Have I to append the list in the init method ?
>>
>> Thank you for ready.
>>
>>
>>
>> --
>> Brookes Christopher.
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multiples python files

2011-02-28 Thread Izz ad-Din Ruhulessin
Hi, you must pass the herosAll list to the DisplayAll() method like this

class Character():
@classmethod
def DisplayAll(herosAll):
print ('There is', Character.CharacterCount, 'heros')
for heros in herosAll:
heros.DisplayCharacterInfos()

herosAll = [
 Character(1,"Antaa","Soldat moins fort",15,5,8),
 Character(2,"Klaitos","Soldat moins fort",15,5,8)]

Character.DisplayAll(herosAll)


2011/2/28 Christopher Brookes 

> Hi, first sorry for my poor english, i'm a french guy, i'm trying to make
> the best :(
>
> I would like to split my python script into multiples files.
> I want :
> A file which contains only class creations and methods,
> A file with some personals functions
> And a main.py which is the main script.
>
> But i'm getting some problems
> In class creation file, i've a init method which create a character  (it
> works).
> They are created in main.py like this :
>
> herosAll = [
>  Character(1,"Antaa","Soldat moins fort",15,5,8),
>  Character(2,"Klaitos","Soldat moins fort",15,5,8)]
>
> But when i want to display all information about my character with :
>
> class Character():
> def DisplayAll():
> print ('There is', Character.CharacterCount, 'heros')
> for heros in herosAll:
> heros.DisplayCharacterInfos()
>
> I'm getting :
>
> Traceback (most recent call last):
>   File "main.py", line 28, in 
> Character.DisplayAll()
>   File "/home/christopher/class_creation.py", line 53, in DisplayAll
> for heros in herosAll:
> NameError: global name 'herosAll' is not defined
>
> I know the source of the problem. The list herosAll is declared in main.py
> so he can't access to it. But i'm stuck here. How can he get it ?
> Have I to append the list in the init method ?
>
> Thank you for ready.
>
>
>
> --
> Brookes Christopher.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] remote code execution

2011-02-15 Thread Izz ad-Din Ruhulessin
Just tested that, doesn't work.

Have you considered installing SVN or any other version control system?

2011/2/15 Izz ad-Din Ruhulessin 

> Send your code as a raw text string and use eval on it maybe
>
> 2011/2/15 ian douglas 
>
>>  Sounds like it should be possible via SSH, but I have no idea how you'd
>> set that up within Eclipse.
>>
>>
>> On 02/15/2011 10:50 AM, S de Haan wrote:
>>
>> For instance, Im working on my local machine with Eclipse, but using the
>> Interpreter that is on one of my Linux Servers.
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] remote code execution

2011-02-15 Thread Izz ad-Din Ruhulessin
Send your code as a raw text string and use eval on it maybe

2011/2/15 ian douglas 

>  Sounds like it should be possible via SSH, but I have no idea how you'd
> set that up within Eclipse.
>
>
> On 02/15/2011 10:50 AM, S de Haan wrote:
>
> For instance, Im working on my local machine with Eclipse, but using the
> Interpreter that is on one of my Linux Servers.
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class question

2011-01-26 Thread Izz ad-Din Ruhulessin
class Raw ---> class Processor ---> class Final

2011/1/26 Tino Dai 

>
>
>>
>> A raw casting comes into a factory.  It is listed as such.  When machined,
>> this part number changes to a different part number.   The raw casting has
>> no "quality related" stuff, but the machined casting does, and it can have
>> more than one "quality related" thing.
>>
>> ...because, the raw casting may go through multiple operations to get to
>> it's final state.  It may get machined on a lathe, then be transferred to a
>> CNC machining station where a bolt circle may be drilled and tapped into
>> it.  Each of those operations on separate machines will have a different set
>> of quality checks associated with it.
>>
>> ...or it might be a part that goes from a raw casting to a sort of
>> "mini-assembly" such as a rocker lever (if you know what that is), so we
>> have raw casting = one part number, then it gets a bushing pressed into it =
>> another part number, then it gets a threaded insert = another part number,
>> but it is still the same thing, and each one of those steps may have some
>> sort of quality check involved.
>>
>> Lets complicate things even further.  One raw casting may be machined into
>> multiple part numbers.  Perhaps the only thing that changes is the location
>> of a single hole.  But again, each one of those part numbers may go through
>> multiple machining operations on different machines, with different quality
>> checks.  This is done through something called a "tabbed" blueprint, wherein
>> there is a master number, but there are "tabs" indicating that if you
>> changes such and such feature, then the part number isn't the master number,
>> but the tabbed number.
>>
>> So, in essence, there's a sort of "network" of "is-a" and "has-a"
>> information.
>>
>> My idea was to, instead of having just a single "part" class, to have a
>> sort of "component aggregate" class, which would cover not only single
>> parts, but assemblies of parts.  So, even if a part was as simple as a raw
>> casting that is just machined into a finished part and that's it, it would
>> still be treated as a sort of assembly, with the raw casting being a
>> component of the finished part number, if that makes sense.
>>
>> So there's all this information associated with a given part.  I am
>> thinking it has a sort of tree structure.  I am just wondering if some of
>> the branches of the tree should be separate classes that are then tied into
>> the "trunk" of the master class, or if the whole thing should be a tree into
>> and of itself.
>>
>> ...and yeah, I know, it's kind of a complex problem for a newbie to be
>> thinking about.
>>
>>
>>
>>
> Here is my two-cents. This code is untested. Import statements haven't been
> included, there could be syntax errors, etc etc etc. What I did
> was switching off the part_number attribute in the Thing class. For the
> functions that "do stuff" to the thing instance, I appended a part-number
> (assuming new part number = master number + doing stuff number). The quality
> functions will check for that part number before proceeding with the checks.
>
>
> class Thing:   # single part class
>  def __init__(self,part_number='12345'):   # 12345 is a default
> part number
>   self.part_number=part_number
>
> def routeThing(thing):
>  try:
>  thing.part_number.append('-someRoutingPartNumber')
>  
>  exception AttributeError (e):
>   e.printStackTrace()
>   print "Router was not applied to thing"
>
> def checkQualityRoute1(thing):
>  if hasattrib(thing,part_number) &&
> (thing.part_number.find('-someRoutingPartNumber'):
> 
>  else:
>  print "Thing has not be routed yet"
>
> def checkQualityRoute2(thing):
>  if hasattrib(thing,part_number) &&
> (thing.part_number.find('-someRoutingPartNumber'):
> 
>  else:
>  print "Thing has not be routed yet"
>
>  continue for all of the functions that you might need
>
> HTH,
> -Tino
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] The trap of the year

2011-01-25 Thread Izz ad-Din Ruhulessin
Or the internal memory id or whatever it's called.

2011/1/25 Izz ad-Din Ruhulessin 

> I think it has something to do with the physical id of the object
>
> 2011/1/25 Karim 
>
>
>> Hello All,
>>
>> Just to share on rageous bug I encounter where 2 lists which "should" to
>> be different (same id) because hold by different instances of the same class
>> are not in fact DIFFERENT, see below:
>>
>> >>> class Device():
>> ... def __init__(self, parameters=[]):
>> ... self.parameters = parameters
>> ... def param(self):
>> ... print(id(self.parameters))
>> ...
>> >>> a=Device()
>> >>> b=Device()
>> >>> a.param()
>> 140559202956568
>> >>> b.param()
>> 140559202956568
>>
>> When I discovered that I was puzzled because at the prompt:
>>
>> >>> a = []
>> >>> b = []
>> >>> id(a)
>> 140559202956496
>> >>> id(b)
>> 140559202957000
>>
>> I am not really understanding why my init in the class made it refers to
>> the same list object.
>> What is the difference with 2nd example directly at the prompt?
>>
>> By the way, this one is ok:
>>
>> >>> class Device():
>> ... def __init__(self,parameters=None):
>> ... self.parameters = None
>> ... self.parameters = []
>> ... def param(self):
>> ... print(id(self.parameters))
>> ...
>> >>> a=Device()
>> >>> b=Device()
>> >>> b.param()
>> 140559202956496
>> >>> a.param()
>> 140559202956568
>>
>> Karim
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] The trap of the year

2011-01-25 Thread Izz ad-Din Ruhulessin
I think it has something to do with the physical id of the object

2011/1/25 Karim 

>
> Hello All,
>
> Just to share on rageous bug I encounter where 2 lists which "should" to be
> different (same id) because hold by different instances of the same class
> are not in fact DIFFERENT, see below:
>
> >>> class Device():
> ... def __init__(self, parameters=[]):
> ... self.parameters = parameters
> ... def param(self):
> ... print(id(self.parameters))
> ...
> >>> a=Device()
> >>> b=Device()
> >>> a.param()
> 140559202956568
> >>> b.param()
> 140559202956568
>
> When I discovered that I was puzzled because at the prompt:
>
> >>> a = []
> >>> b = []
> >>> id(a)
> 140559202956496
> >>> id(b)
> 140559202957000
>
> I am not really understanding why my init in the class made it refers to
> the same list object.
> What is the difference with 2nd example directly at the prompt?
>
> By the way, this one is ok:
>
> >>> class Device():
> ... def __init__(self,parameters=None):
> ... self.parameters = None
> ... self.parameters = []
> ... def param(self):
> ... print(id(self.parameters))
> ...
> >>> a=Device()
> >>> b=Device()
> >>> b.param()
> 140559202956496
> >>> a.param()
> 140559202956568
>
> Karim
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exactly duplicating strftime behavior?

2011-01-17 Thread Izz ad-Din Ruhulessin
Hi Hugo,

Problem solved, thanks!

Kind regards,

Izz ad-Din

2011/1/17 Hugo Arts 

> On Mon, Jan 17, 2011 at 8:29 PM, Izz ad-Din Ruhulessin
>  wrote:
> > Hi all,
> > I'm designing a module which aims to provide full compatibility with
> > Pythons' datetime module.
> > However, I can't find out how some operators in strftime function,
> namely:
> > those who use the locale. (%a, %A, %b, etc.)
> > How do I access this locale and it's values?
> > Thanks in advance.
> > Kind regards,
> > Izz ad-Din
>
> Check out the locale module:
>
> http://docs.python.org/library/locale.html#locale.nl_langinfo
>
> HTH,
> Hugo
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why super does not work !

2011-01-17 Thread Izz ad-Din Ruhulessin
It looks like because of something Observable doesn't have that attribute.
Could you post the ListBox class?

2011/1/17 Karim 

>
>
> Hello,
>
> I implemented Observer DP on a listbox (Tkinter) as follows and I don't
> understand why super() is not working and Observable.__init__(self) is
> working, cf below:
>
> class ListObservable(Listbox, Observable):
> """Creation de widget Listbox"""
> def __init__(self):
> super(ListObservable, self).__init__()
> #Observable.__init__(self)
> self._value = None
> self.listeContenu = StringVar()
> self.listeContenu.set(' '.join(sorted(data_base.keys(
> self.liste = Listbox(listvariable=self.listeContenu,
> selectmode='single')
> self.liste.grid(row=0, column=1, sticky=N+S+W)
> self.liste.bind('', self.onSelect)
>
> *The error is:*
> Traceback (most recent call last):
>   File "./observerAppliGraphique.py", line 118, in 
> app=App()
>   File "./observerAppliGraphique.py", line 37, in __init__
> self.sujet.attach(self.nom)
>   File "/home/karim/guiObserver/observable.py", line 11, in attach
> self._observers.append(observer)
> AttributeError: 'ListObservable' object has no attribute '_observers'
>
> And the Observable class is:
>
> class Observable(object):
> """Sujet a observer"""
> def __init__(self):
> self._observers = []
> print('constructeur observable')
>
> def attach(self, observer):
> """Attache un nouvel observateur"""
> self._observers.append(observer)
>
> def detach(self, observer):
> """Retire un nouvel observateur"""
> self._observers.remove(observer)
>
> def notify(self):
> """Avertit tous les observateurs que l'observable change d'etat"""
> for observer in self._observers:
> observer.update()
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Exactly duplicating strftime behavior?

2011-01-17 Thread Izz ad-Din Ruhulessin
Hi all,

I'm designing a module which aims to provide full compatibility with
Pythons' datetime module.

However, I can't find out how some operators in strftime function, namely:
those who use the locale. (%a, %A, %b, etc.)

How do I access this locale and it's values?

Thanks in advance.

Kind regards,

Izz ad-Din
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Refcount in C extensions

2011-01-17 Thread Izz ad-Din Ruhulessin
Hi Steve,

Your remarks about Cython pushed me over the edge into the Unknown, this
weekend I decided to download it and check it out.

I've been using it the past few days and it totally rocks. It really feels
like I was chained before and now I'm not; like where some simple Python
operations could require tens or even hundreds of lines of code, Cython make
life easiër. A real life-saver, thanks!

I also like how simple it is to import C functions to python, btw.

Kind regards,

Izz ad-Din

2011/1/14 Stefan Behnel 

> Izz ad-Din Ruhulessin, 14.01.2011 19:49:
>
>  Thanks for your quick reply and clearing the issue up for me. Using your
>> answer, I rewrote the function to this:
>>
>> double Py_GetAttr_DoubleFromFloat(PyObject *obj, const char *attr)
>>
>>>
>>> {
>>>
>>> PyObject *get_attr, *py_float;
>>>
>>> int has_attr;
>>>
>>>
>>>  //Check if the given object has the given attribute.
>>>>
>>>
>>> has_attr = PyObject_HasAttrString(obj, attr);
>>>
>>> if (has_attr == False) {
>>>
>>> return -.0;
>>>
>>> }
>>>
>>>
>>>  //Get our attribute and convert it to a double.
>>>>
>>>
>>> get_attr = PyObject_GetAttrString(obj, attr);
>>>
>>
> Note that HasAttr() calls GetAttr() internally, so it's actually faster to
> call GetAttr() and check for an exception (and clear it). That's basically
> how HasAttr() works, except that it doesn't tell you the result if the
> attribute existed.
>
>
>
>  py_float = PyNumber_Float(get_attr);
>>>
>>> if (py_float == NULL) {
>>>
>>> Py_DECREF(get_attr);
>>>
>>> Py_XDECREF(py_float);
>>>
>>
> You already know that py_float is NULL, so Py_XDECREF() is a no-op.
>
>
>
>  return -.0;
>>>
>>> }
>>>
>>> double output = PyFloat_AsDouble(py_float);
>>>
>>>
>>>  //Garbage collect
>>>>
>>>
>>> Py_DECREF(get_attr);
>>>
>>> Py_XDECREF(py_float);
>>>
>>
> py_float cannot be NULL at this point, so the Py_XDECREF() will compile
> into Py_DECREF().
>
>
>  (False is 0)
>>
>
> In that case, better write 0 instead.
>
>
>
>  Regarding your Cython suggestion, as a matter of coincidence I have been
>> reading about it in the past few days. I'm in doubt of using it however,
>> because I have a lot of native C code that would require rewriting if I
>> switched to Cython.
>>
>
> No need for that, Cython can call external C code natively. So you can make
> the switch step by step.
>
>
>
>  On the other hand, your example shows that such a
>> one-time rewrite will pay-off big time in future development speed.
>>
>
> It usually does, yes. It often even pays off immediately because a rewrite
> tends to be pretty straight forward (basically, read and understand the C
> code, rip out all low-level stuff and replace the rest with simpler code),
> and while doing so, some bugs tend to disappear, the code becomes simpler,
> safer and often also faster, and new features appear while you're at it.
>
>
> Stefan
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python on Ubuntu 10.10?

2011-01-15 Thread Izz ad-Din Ruhulessin
Although I probably wont switch from Eclipse to vim, that looks nevertheless
very, very nice, bookmarked.

2011/1/15 Sean Carolan 

> >>> I am new to programming and to Python.  I've been using Python with
> IDLE
> >>> on Windows Vista for a few weeks now.
> >>> (And I'm loving it!)  However, I'm thinking about switching to Ubuntu
> >>> 10.10.  If I download Ubuntu, will I still be able to use the
> >>> IDLE environment?  I am really quite fond of it (mostly because it's
> what
> >>> I know!).  To use Python in Ubuntu,
> >>> will I have to do any additional downloading, or do Python and IDLE
> come
> >>> built in and ready to use?
>
> Bite the bullet and learn how to use vim; you won't regret it.
> There's a steep learning curve at first but once you get the hang of
> it you'll be coding like a boss.  This blog post also has some great
> tips on how to make vim into an IDE:
>
> http://dancingpenguinsoflight.com/2009/02/python-and-vim-make-your-own-ide/
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python on Ubuntu 10.10?

2011-01-15 Thread Izz ad-Din Ruhulessin
Install Eclipse via Synaptic and then PyDev via Eclipse.

2011/1/15 Timo 

> On 15-01-11 02:17, Joel Knoll wrote:
>
>> Hello,
>>
>> I am new to programming and to Python.  I've been using Python with IDLE
>> on Windows Vista for a few weeks now.
>> (And I'm loving it!)  However, I'm thinking about switching to Ubuntu
>> 10.10.  If I download Ubuntu, will I still be able to use the
>> IDLE environment?  I am really quite fond of it (mostly because it's what
>> I know!).  To use Python in Ubuntu,
>> will I have to do any additional downloading, or do Python and IDLE come
>> built in and ready to use?
>>
>>  You should try the default text editor that comes with Ubuntu, called
> Gedit. You can tweak it very nicely so it shows linenumbers and so on. There
> are also very useful plugins. It is all I ever use and when I need to write
> some code in Windows, it bugs me how bad IDLE really is.
>
> Cheers,
> Timo
>
>  Thanks for your time,
>>
>> JC Knoll
>>
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Refcount in C extensions

2011-01-14 Thread Izz ad-Din Ruhulessin
Hi Stefan,

Thanks for your quick reply and clearing the issue up for me. Using your
answer, I rewrote the function to this:

double Py_GetAttr_DoubleFromFloat(PyObject *obj, const char *attr)
>
> {
>
> PyObject *get_attr, *py_float;
>
> int has_attr;
>
>
>> //Check if the given object has the given attribute.
>
> has_attr = PyObject_HasAttrString(obj, attr);
>
> if (has_attr == False) {
>
> return -.0;
>
> }
>
>
>> //Get our attribute and convert it to a double.
>
> get_attr = PyObject_GetAttrString(obj, attr);
>
> py_float = PyNumber_Float(get_attr);
>
> if (py_float == NULL) {
>
> Py_DECREF(get_attr);
>
> Py_XDECREF(py_float);
>
> return -.0;
>
> }
>
> double output = PyFloat_AsDouble(py_float);
>
>
>> //Garbage collect
>
> Py_DECREF(get_attr);
>
> Py_XDECREF(py_float);
>
>
>> return output;
>
> }
>
>
(False is 0)

Regarding your Cython suggestion, as a matter of coincidence I have been
reading about it in the past few days. I'm in doubt of using it however,
because I have a lot of native C code that would require rewriting if I
switched to Cython. On the other hand, your example shows that such a
one-time rewrite will pay-off big time in future development speed.

Kind regards,

Izz ad-Din
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Refcount in C extensions

2011-01-14 Thread Izz ad-Din Ruhulessin
Hello,

I am writing a Python C extension and I have some trouble understanding how
reference counting works exactly. Though I think I understand the practice
on simple operations (see my question at stackoverflow:
http://stackoverflow.com/questions/4657764/py-incref-decref-when), but on
more "complex" operations I cannot quite grasp it yet.

For example, in the following helper function, do I need to DECREF or are
all the references automatically destroyed when the function returns?

double Py_GetAttr_DoubleFromFloat(PyObject *obj, const char *attr)
{
if ((PyObject_GetAttrString(obj, attr) == False) ||
(PyObject_HasAttrString(obj, attr) == False)) {
return -.0;
}

return PyFloat_AsDouble(PyNumber_Float(PyObject_GetAttrString(obj, attr)));
}

Please share your thoughts, thanks in advance, kind regards,

Izz ad-Din
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor