increment date present list of tuple by weeks python

2012-05-11 Thread Nikhil Verma
Hi All


I have a list like this :-

[ ('7 May monday AM Neuropancreatic'), ('8 May tuesday PM Cardiovascular')]

how can i increment date in the above list for the next  months on weekly
basis ?

[ ('7 May monday AM Neuropancreatic'),('14May monday AM
Neuropancreatic')('21 May monday AM Neuropancreatic')('28 May monday AM
Neuropancreatic'),
 ('8 May tuesday PM Cardiovascular'),('15 May monday AM
Neuropancreatic'),('22 May monday AM Neuropancreatic'),('29 May monday AM
Neuropancreatic')]


Thanks



-- 
Regards
Nikhil Verma
+91-958-273-3156
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: increment date present list of tuple by weeks python

2012-05-11 Thread Mark Lawrence

On 11/05/2012 10:55, Nikhil Verma wrote:

Hi All


I have a list like this :-

[ ('7 May monday AM Neuropancreatic'), ('8 May tuesday PM Cardiovascular')]

how can i increment date in the above list for the next  months on weekly
basis ?

[ ('7 May monday AM Neuropancreatic'),('14May monday AM
Neuropancreatic')('21 May monday AM Neuropancreatic')('28 May monday AM
Neuropancreatic'),
  ('8 May tuesday PM Cardiovascular'),('15 May monday AM
Neuropancreatic'),('22 May monday AM Neuropancreatic'),('29 May monday AM
Neuropancreatic')]


Thanks



See http://docs.python.org/library/time.html#time.strptime and it's 
cousin strftime, and 
http://docs.python.org/library/datetime.html#module-datetime date and 
timedelta types.


--
Cheers.

Mark Lawrence.

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


Re: Finding the line number of an 'else' statement via ast

2012-05-11 Thread Mark Lawrence

On 11/05/2012 05:35, Michael Rene Armida wrote:

Given this source:

def do_something(val):
 if val:
 return 'a'
 else:
 return 'b'

How do I get the line number of the "else:" line, using the ast
module?  The grammar only includes the 'orelse' list:

 If(expr test, stmt* body, stmt* orelse)

...but 'orelse' is the list of statements under the 'else' token, not
a node representing the token itself.

I have a suspicion that this isn't possible, and shouldn't be, and the
giveaway word above was "token."  Because the tokens themselves aren't
part of the abstract syntax tree.

Here's an interactive session showing me poking around the If node:


import ast
tree = ast.parse('''

... if True:
... pass
... else:
... pass
... ''')

tree.body[0].orelse

[<_ast.Pass object at 0x7f1301319390>]

tree.body[0]._fields

('test', 'body', 'orelse')

for i in ast.iter_child_nodes(tree.body[0]):

... print i.__class__.__name__
...
Name
Pass
Pass


Is my suspicion correct?  Or is there a way to get the line number of
that 'else:'?


Get the line number of the first pass and add one?

--
Cheers.

Mark Lawrence.

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


How can we covert string into Datetime object

2012-05-11 Thread Nikhil Verma
Hi All

I was going through this link
http://docs.python.org/library/datetime.html#strftime-strptime-behavior.
I practised strftime() and strptime() functions.

Finally i stuck into a situation where  i want to get the datetime object
so that i can save it in my db.
What i want is :-

I have a string let say
date_created = '11 May Friday PM '

and i want to convert it into datetime object like this
datetime.datetime(2012, 5, 11, 4, 12, 44, 24734)

Thanks in advance. Any help will be appreciated

-- 
Regards
Nikhil Verma
+91-958-273-3156
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Dealing with the __str__ method in classes with lots of attributes

2012-05-11 Thread Andreas Tawn
> This issue bit me once too often a few months ago, and now I have a class 
> called
> "O" from which I often subclass instead of from "object".
> Its main purpose is a friendly __str__ method, though it also has a friendly 
> __init__.
> 
> Code:
> 
> class O(object):
>   ''' A bare object subclass to allow storing arbitrary attributes.
>   It also has a nicer default str() action, and an aggressive repr().
>   '''
> 
>   def __init__(self, **kw):
> ''' Initialise this O.
> Fill in attributes from any keyword arguments if supplied.
> This call can be omitted in subclasses if desired.
> '''
> for k in kw:
>   setattr(self, k, kw[k])
> 
>   def __str__(self):
> return ( "<%s %s>"
>  % ( self.__class__.__name__,
>  ",".join([ "%s=%s" % (attr, getattr(self, attr))
> for attr in sorted(dir(self)) if 
> attr[0].isalpha()
>   ])
>)
>)

This is a very interesting solution.

I think it might be better suited (for my purpose) to __repr__ rather than 
__str__, mostly because I still lose control of the order the attributes appear.

I really like the general idea of subclassing object though, because I often 
have classes with dozens of attributes and __init__ gets very messy.

Chris' dynamically generated format string looks to be my best bet in the 
absence of a perfect solution.

Cheers,

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


Re: How can we covert string into Datetime object

2012-05-11 Thread MRAB

On 11/05/2012 12:13, Nikhil Verma wrote:

Hi All

I was going through this link
http://docs.python.org/library/datetime.html#strftime-strptime-behavior.
I practised strftime() and strptime() functions.

Finally i stuck into a situation where  i want to get the datetime
object so that i can save it in my db.
What i want is :-

I have a string let say
date_created = '11 May Friday PM '

and i want to convert it into datetime object like this
datetime.datetime(2012, 5, 11, 4, 12, 44, 24734)

Thanks in advance. Any help will be appreciated


As it says in the documentation:

%d matches the day of the month
%B matches the name of the month
%A matches the day of the week
%p matches AM/AM

so:


datetime.datetime.strptime('11 May Friday PM', '%d %B %A %p')

datetime.datetime(1900, 5, 11, 0, 0)

(I've stripped off the trailing space.)

Note that as you haven't supplied a year, the year defaults to 1900,
and as you haven't supplied an hour but only "PM", the hour defaults to
0 (and there's no way to tell whether it was AM or PM). (The minutes
and seconds also default to 0.)

You can't convert something as vague as '11 May Friday PM' to a
datetime object.

If all of the times are just AM/PM you could try appending an hour (eg
'12') before parsing and ignore it when you convert it back to a string
for display.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dealing with the __str__ method in classes with lots of attributes

2012-05-11 Thread Dave Angel
On 05/11/2012 07:16 AM, Andreas Tawn wrote:
>> 
>> This is a very interesting solution.
>>
>> I think it might be better suited (for my purpose) to __repr__ rather than 
>> __str__, mostly because I still lose control of the order the attributes 
>> appear.

I have no idea why using __repr__ versus __str__ would make any
difference in the order of the attributes. They're going to come out in
the order you specify, regardless of what you name your method.  If you
don't like the arbitrary order you get from the dictionary, then either
sort it, or provide an explicit list.



-- 

DaveA

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


RE: Dealing with the __str__ method in classes with lots of attributes

2012-05-11 Thread Andreas Tawn
> I have no idea why using __repr__ versus __str__ would make any difference in 
> the
> order of the attributes. They're going to come out in the order you specify,
> regardless of what you name your method.  If you don't like the arbitrary 
> order you
> get from the dictionary, then either sort it, or provide an explicit list.

Only that, as the docs say, __repr__ should represent the entire object that 
could be used to build a new object with the same value. For that task the 
order of the attributes is immaterial.

I want __str__ to give me something easily readable and ordered in a way that's 
conveys some meaning about the attributes. It's also helpful to not have to 
display every attribute, of which there may be dozens.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dealing with the __str__ method in classes with lots of attributes

2012-05-11 Thread Mark Lawrence

On 11/05/2012 15:32, Andreas Tawn wrote:


It's also helpful to not have to display every attribute, of which there may be 
dozens.


Do I detect a code smell here?

--
Cheers.

Mark Lawrence.

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


Re: Finding the line number of an 'else' statement via ast

2012-05-11 Thread Terry Reedy

On 5/11/2012 12:35 AM, Michael Rene Armida wrote:

Given this source:

def do_something(val):
 if val:
 return 'a'
 else:
 return 'b'

How do I get the line number of the "else:" line, using the ast
module?  The grammar only includes the 'orelse' list:

 If(expr test, stmt* body, stmt* orelse)

...but 'orelse' is the list of statements under the 'else' token, not
a node representing the token itself.

I have a suspicion that this isn't possible, and shouldn't be, and the
giveaway word above was "token."  Because the tokens themselves aren't
part of the abstract syntax tree.


The main reason to record line numbers in the parse tree and hence the 
CPython code object is to print the line number and corresponding line 
in exception tracebacks. Since 'else:' on a line by itself is not a 
statement in itself and does not contain an expression that could raise, 
there is no need to record a line number. So I would not be surprised if 
it is not directly recorded.


'else: 1/0' and "elif 1/0" will have recorded line numbers.

If you can get the last line of the if-block and first line of the 
else-block, and there is a gap, you might guess that the else is in 
between ;-).


--
Terry Jan Reedy

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


Re: Dealing with the __str__ method in classes with lots of attributes

2012-05-11 Thread Jean-Michel Pichavant

Mark Lawrence wrote:

On 11/05/2012 15:32, Andreas Tawn wrote:

It's also helpful to not have to display every attribute, of which 
there may be dozens.


Do I detect a code smell here?

I think so, Murphy's law dictates that the attribute you're interested 
in will not be displayed anyway.


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


RE: Dealing with the __str__ method in classes with lots of attributes

2012-05-11 Thread Andreas Tawn
> > It's also helpful to not have to display every attribute, of which there 
> > may be
> dozens.
> 
> Do I detect a code smell here?

Possibly. I'll often try to subdivide into several simpler types, but sometimes 
that makes the code more complex than it needs to be.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Dealing with the __str__ method in classes with lots of attributes

2012-05-11 Thread Andreas Tawn
> >> It's also helpful to not have to display every attribute, of which
> >> there may be dozens.
> >
> > Do I detect a code smell here?
> >
> I think so, Murphy's law dictates that the attribute you're interested in 
> will not be
> displayed anyway.

That's what __repr__'s for.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie naive question ... int() throws ValueError

2012-05-11 Thread Terry Reedy

On 5/11/2012 1:55 AM, John Terrak wrote:


I couldnt find anywhere in the documentation that int() can throw a ValueError.
I checked the "The Python Language Reference", and the "The Python
Standard Library " to no avail.
Did I missed something?


To add to Chris' answer:

If the domain of a function is truly all Python objects, it cannot raise 
an error. I believe id(x) is such an example.


Even if the domain is intended to be all Python objects, you cannot be 
sure if the function uses any special method defined on the object or 
its class. For examples, type(x) *should* always work, but I would not 
be surprised if a buggy __getattribute__ method or buggy metaclass could 
result in an exception instead.


If the arguments for a function include a function, for example map(f, 
'abc'), then the passed function can raise any exception and hence the 
called function will pass along the exception unless, unusually, it 
catches it.


As to your specific question, if the domain of a function is a subset of 
types and values of allowed types, then you should expect that it can 
raise either TypeError or ValueError.

If the domain


So here is the question - if it is not in the documentation - how does
one find out the
exceptions that are thrown by a constructor, a method or a function?


One way is to try specific examples, as you did. Following what Chris 
said, especially do that for bad input whose exception you want to 
catch. Sometimes this is faster than trying to find the answer in the 
doc, and it gives the actual answer rather than the intended answer.



Example:  int("not_an_int")

int("not_an_int")

Traceback (most recent call last):
   File "", line 1, in
ValueError: invalid literal for int() with base 10: 'not_an_int'


Some strings are legal input, hence not a TypeError, but not all, hence 
ValueError.



From what I gathered:

class int(object):
   """ int(x[, base]) ->  integer

   Convert a string or number to an integer, if possible.  A floating point
   argument will be truncated towards zero (this does not include a string
   representation of a floating point number!)  When converting a string, use
   the optional base.  It is an error to supply a base when converting a
   non-string.  If base is zero, the proper base is guessed based on the
   string content.  If the argument is outside the integer range a
   long object will be returned instead. """


'error' should say 'TypeError' as it is a TypeError to provide the wrong 
number of args. However, the current 3.3 manual entry is more accurate 
and informative, starting with the signature.


--
Terry Jan Reedy

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


Re: Newbie naive question ... int() throws ValueError

2012-05-11 Thread Christian Heimes
Am 11.05.2012 17:51, schrieb Terry Reedy:
> If the domain of a function is truly all Python objects, it cannot raise
> an error. I believe id(x) is such an example.

Even id() can raise an exception, for example MemoryError when you are
running out of memory.

Christian

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


Re: Newbie naive question ... int() throws ValueError

2012-05-11 Thread Chris Angelico
On Sat, May 12, 2012 at 2:15 AM, Christian Heimes  wrote:
> Am 11.05.2012 17:51, schrieb Terry Reedy:
>> If the domain of a function is truly all Python objects, it cannot raise
>> an error. I believe id(x) is such an example.
>
> Even id() can raise an exception, for example MemoryError when you are
> running out of memory.

KeyboardInterrupt can also be raised at (effectively) any time, but
I'm not sure that that really counts as id() raising the exception. If
I understand it correctly, MemoryError would be because the
interpreter can't allocate an int object for id's return value.

But these are definitely part of why you don't just catch all exceptions.

Hmm. What happens if the interpreter can't construct a MemoryError exception?

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


__all__, public API, private stuff, and leading _

2012-05-11 Thread Ethan Furman

Style question:

Since __all__ (if defined) is the public API, if I am using that should 
I also still use a leading underscore on my private data/functions/etc?


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


Re: __all__, public API, private stuff, and leading _

2012-05-11 Thread Emile van Sebille

On 5/11/2012 9:41 AM Ethan Furman said...

Style question:

Since __all__ (if defined) is the public API, if I am using that should
I also still use a leading underscore on my private data/functions/etc?


I would, even if only to alert any future maintainer of the internal vs 
exposed nature of things.


Emile


















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


Re: Newbie naive question ... int() throws ValueError

2012-05-11 Thread Ian Kelly
On Fri, May 11, 2012 at 10:23 AM, Chris Angelico  wrote:
> Hmm. What happens if the interpreter can't construct a MemoryError exception?

I believe that a MemoryError instance is pre-allocated for just this
scenario.  You can see it in the result of gc.get_objects().

>>> [x for x in gc.get_objects() if isinstance(x, MemoryError)]
[MemoryError()]

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


Re: Newbie naive question ... int() throws ValueError

2012-05-11 Thread Chris Angelico
On Sat, May 12, 2012 at 3:12 AM, Ian Kelly  wrote:
> I believe that a MemoryError instance is pre-allocated for just this
> scenario.

Ah, wise move. It's one of those largely-imponderables, like figuring
out how to alert the sysadmin to a router failure.

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


Re: Retrieving result from embedded execution

2012-05-11 Thread Devin Jeanpierre
On Fri, May 11, 2012 at 12:45 AM, Stefan Behnel  wrote:
> However, have you tried using a pipe for them instead of a real file? That
> would allow you to retrieve the output without needing to pass through a
> file in the file system. You can also replace sys.stdout/err with arbitrary
> objects in Python space, which could then forward the output in any way you
> want.

Surely a pipe would cause a deadlock if the pipe fills up if Python
and the C program are running in the same process/thread?

I'm not too familiar with these sorts of things.

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


Re: Retrieving result from embedded execution

2012-05-11 Thread Chris Angelico
On Sat, May 12, 2012 at 3:36 AM, Devin Jeanpierre
 wrote:
> On Fri, May 11, 2012 at 12:45 AM, Stefan Behnel  wrote:
>> However, have you tried using a pipe for them instead of a real file? That
>> would allow you to retrieve the output without needing to pass through a
>> file in the file system. You can also replace sys.stdout/err with arbitrary
>> objects in Python space, which could then forward the output in any way you
>> want.
>
> Surely a pipe would cause a deadlock if the pipe fills up if Python
> and the C program are running in the same process/thread?

Yes, it would; how much data are you looking at retrieving, and is it
all at script-end or do you need to process it concurrently? If the
latter, then your two best options are a pipe (and running the Python
script in another thread, possibly a separate process) or a callback
of some sort (in which case the script hands you a line or block of
output and says "Deal with this and get back to me") - eg by replacing
sys.stdout, or defining a function that the Python script calls
explicitly.

This is starting to sound similar to something I did at work. A C++
program uses a block of Python code as a sort of uber-config-file. It
would initialize the Python environment, import some modules, etc,
once, and keep the globals around (this allows Python globals to be
retained). Every time script-configurable code is to be run:

1) Prepare a dictionary called Input with a whole lot of
parameters/information/etc
2) Create an empty dictionary and call it Output
3) Execute a block of code (retrieved from the database)
4) Inspect the Output dictionary and use that to control subsequent behaviour.

As a concept, it worked quite well. I do not, however, advise doing
this if your Python scripts come from untrusted sources, as it is
impossible to guarantee safety. (For that reason we actually shifted
to Javascript for that project.) But if you're using this as a
powerful and simple config-file and you know you can trust everything
that will be run, then it's a pretty awesome way of doing things. It
takes deliberately malicious code to break the system.

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


Re: __all__, public API, private stuff, and leading _

2012-05-11 Thread Ethan Furman

Emile van Sebille wrote:

On 5/11/2012 9:41 AM Ethan Furman said...

Style question:

Since __all__ (if defined) is the public API, if I am using that should
I also still use a leading underscore on my private data/functions/etc?


I would, even if only to alert any future maintainer of the internal vs 
exposed nature of things.


I find that a persuasive argument, thanks.

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


Re: Newbie naive question ... int() throws ValueError

2012-05-11 Thread John Terrak
Thank you all for your help.
Greatly appreciated.

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


Re: Newbie naive question ... int() throws ValueError

2012-05-11 Thread Devin Jeanpierre
On Fri, May 11, 2012 at 2:10 AM, Chris Angelico  wrote:
> Unlike in Java, a function's list of things it can throw isn't part of
> its signature. Instead of trying to catch every possible exception,
> it's generally best to simply let exceptions propagate unless you KNOW
> you're expecting them.

How am I supposed to know to expect them, if they are undocumented?
Trial and error? That seems like a poor replacement for documented
error conditions.

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


Re: Dealing with the __str__ method in classes with lots of attributes

2012-05-11 Thread Cameron Simpson
On 11May2012 15:40, Mark Lawrence  wrote:
| On 11/05/2012 15:32, Andreas Tawn wrote:
| > It's also helpful to not have to display every attribute, of which there 
may be dozens.
| 
| Do I detect a code smell here?

Not necessarily. (Well, yeah, "dozens" may indicate time to partition
stuff.) My "O" class (back in the thread) deliberately shows only the
[a-z]* attributes so the user gets the public object state without the
noise of private attributes.

For __repr__ I might print everything. Haven't gone that far yet.

Cheers,
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

That is 27 years ago, or about half an eternity in computer years.
- Alan Tibbetts
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie naive question ... int() throws ValueError

2012-05-11 Thread Chris Angelico
On Sat, May 12, 2012 at 5:34 AM, Devin Jeanpierre
 wrote:
> On Fri, May 11, 2012 at 2:10 AM, Chris Angelico  wrote:
>> Unlike in Java, a function's list of things it can throw isn't part of
>> its signature. Instead of trying to catch every possible exception,
>> it's generally best to simply let exceptions propagate unless you KNOW
>> you're expecting them.
>
> How am I supposed to know to expect them, if they are undocumented?
> Trial and error? That seems like a poor replacement for documented
> error conditions.

Expect exceptions any time anything goes wrong. Don't try to code to
prevent them.

Here's an example. Suppose you write a function that takes a number
and returns that many copies of your club's charter. (Yeah, pretty
stupid, but examples usually are!)

def charter(copies):
return _chartertext * copies

Does this function need to catch any exceptions? No. Can that
expression throw exceptions? Totally! You might be given a non-number
(can't give "foo" copies); you might get a floating point (can't get
three-and-a-half copies); your charter text might have been replaced
with a pizza; the user might hit Ctrl-C right while it's copying; the
number might be so large that you run out of memory; all sorts of
things. But they're not your problems - they're your caller's
problems. If you caught all those exceptions, what would you do? You'd
have to signal the error conditions yourself, which probably means...
raising an exception.

There are times when you want to catch all exceptions, though.
Top-level code will often want to replace exception tracebacks with
error messages appropriate to some external caller, or possibly log
the exception and return to some primary loop. Otherwise, though, most
code will just let unexpected exceptions through.

This is one of those massively freeing leaps of thinking. Java binds
you to a bureaucracy of catching exceptions or declaring them (but
then still has RuntimeException - and I'm sure there've been MANY
programmers who just derive all their exceptions from that); Python
sets you free to care only about what you want to care about.

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


Re: Newbie naive question ... int() throws ValueError

2012-05-11 Thread Devin Jeanpierre
On Fri, May 11, 2012 at 11:21 PM, Chris Angelico  wrote:
> There are times when you want to catch all exceptions, though.
> Top-level code will often want to replace exception tracebacks with
> error messages appropriate to some external caller, or possibly log
> the exception and return to some primary loop. Otherwise, though, most
> code will just let unexpected exceptions through.

I'm not talking about unexpected exceptions. I'm saying, if I expect
invalid input for int, where should I go to find out how to deal with
said invalid input properly? How do I know that int raises ValueError
on failure, and not, for example, something like ArgumentError
(something that Python doesn't have) or (like chr) TypeError?

Apparently the answer is to read the documentation for ValueError.

It's a bit like putting the documentation on the return type for `map`
in the list documentation. Kinda hard to get there without already
knowing the answer.

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


Re: Newbie naive question ... int() throws ValueError

2012-05-11 Thread Chris Angelico
On Sat, May 12, 2012 at 2:11 PM, Devin Jeanpierre
 wrote:
> I'm not talking about unexpected exceptions. I'm saying, if I expect
> invalid input for int, where should I go to find out how to deal with
> said invalid input properly? How do I know that int raises ValueError
> on failure, and not, for example, something like ArgumentError
> (something that Python doesn't have) or (like chr) TypeError?

Ah, I see what you mean.

The easiest way to find out what exception gets thrown is to try it.
For obvious things like int("foo") you can simply test it in the
interactive interpreter; unusual cases you'll discover as you run your
script.

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