Re: Python basic program problem

2011-06-27 Thread Daniel Kluev
On Mon, Jun 27, 2011 at 6:05 PM, Amaninder Singh  wrote:
>>>> print "this is a test"
> SyntaxError: invalid syntax

Most likely, you are running python 3.x, while reading python 2.x book.
In python 3.x print is now ordinary function,

>>> print('hello world')
hello world


In future, please include full tracebacks and python version info.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Bluetooth

2011-06-26 Thread Daniel Kluev
On Mon, Jun 27, 2011 at 2:32 AM, Valentin de Pablo Fouce
 wrote:
> Hi all,
>
> I'm looking for developing a bluetooth application in python, and I'm
> looking for the most suitable python library for it. Googling some
> time I found pyBluez (http://code.google.com/p/pybluez/), however, the
> library seems to be stopped since end 2009 (latest update Nov 2009)
> and not to many work since then. Is there any other library?

blueman is written in python and works fine with latest bluez lib.
It uses dbus for interaction with bluez, you can try using their
wrapper for your own app.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rant on web browsers

2011-06-21 Thread Daniel Kluev
Regarding pyjamas lib size, its actually not that big if you want only
bare python, without DOM wrapper.

You only need pyjslib, which is less than 30kb gzipped when compiled
even with --strict (quite verbose mode).
Even that could be further reduced if you drop unused by your code
python features from it.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Run Python script from JS

2011-06-17 Thread Daniel Kluev
On Fri, Jun 17, 2011 at 9:11 AM, Gnarlodious  wrote:
> Is there any way to call a Py script from Javascript in a webpage?

You can use Pyjamas [1], Emscripten [2] or skulpt [3] for that.

[1] http://pyjs.org/
[2] http://syntensity.com/static/python.html
[3] http://www.skulpt.org/

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scope of function parameters (take two)

2011-05-31 Thread Daniel Kluev
On Wed, Jun 1, 2011 at 3:16 AM, Ian Kelly  wrote:
>
> There is no "decorator" module in the standard library.  This must be
> some third-party module.  The usual way to do this would be:

Yes, but its very useful for decorators and provides some
not-readily-available functionality.
http://pypi.python.org/pypi/decorator/3.3.1

> Note that this will always work, whereas the "decorator.decorator"
> version will break if the decorated function happens to take a keyword
> argument named "f".

No, it will not. Its the magic of decorator library, it is
signature-preserving, while your variant breaks function signature and
causes problems to any code that relies on signatures (happens with
Pylons, for example).

>>> @copy_args
... def test(a, f=None):
... print f
...
>>> test([], f=123)
123

Basically decorator.decorator uses exec to create new function, with
signature of function you pass to your decorator, so it does not
matter what names you used for args in decorator itself.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlalchemy and Unicode strings: errormessage

2011-05-31 Thread Daniel Kluev
On Tue, May 31, 2011 at 8:40 AM, Wolfgang Meiners
 wrote:
> metadata = MetaData('sqlite://')
> a_table = Table('tf_lehrer', metadata,
>    Column('id', Integer, primary_key=True),
>    Column('Kuerzel', Text),
>    Column('Name', Text))

Use UnicodeText instead of Text.

> A_record = A_class('BUM', 'Bäumer')

If this is python2.x, use u'Bäumer' instead.


-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scope of function parameters (take two)

2011-05-31 Thread Daniel Kluev
On Tue, May 31, 2011 at 6:17 PM, Henry Olders  wrote:
> Clearly, making a copy within the function eliminates the possibility of the
> side effects caused by passing in mutable objects. Would having the
> compiler/interpreter do this automatically make python so much different?

As I've pointed, you can make decorator to do that. Adding @copy_args
to each function you intend to be pure is not that hard.

import decorator
import copy

@decorator.decorator
def copy_args(f, *args, **kw):
nargs = []
for arg in args:
nargs.append(copy.deepcopy(arg))
nkw = {}
for k,v in kw.iteritems():
nkw[k] = copy.deepcopy(v)
return f(*nargs, **nkw)

@copy_args
def test(a):
a.append(1)
return a

>>> l = [0]
>>> test(l)
[0, 1]
>>> l
[0]


>>> inspect.getargspec(test)
ArgSpec(args=['a'], varargs=None, keywords=None, defaults=None)

So this decorator achieves needed result and preserves function signatures.


-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scope of function parameters (take two)

2011-05-30 Thread Daniel Kluev
On Tue, May 31, 2011 at 4:13 PM, Wolfgang Rohdewald
 wrote:
> what you really seem to want is that a function by default
> cannot have any side effects (you have a side effect if a
> function changes things outside of its local scope). But
> that would be a very different language than python

This can be done in Python (to some degree), like this

@copy_args
def somefunc(a, b, c):
 ...

where copy_args would explicitly call deepcopy() on all args passed to
the function.
Or, to save some performance, wrap them in some CopyOnEdit proxy
(although this is tricky, as getattr/getitem can modify object too if
class overrides them).

Obviously it would not save you from functions which use
global/globals() or some other ways to change state outside their
scope.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scope of function parameters (take two)

2011-05-30 Thread Daniel Kluev
On Tue, May 31, 2011 at 2:05 PM, Chris Angelico  wrote:
> Infinitely-nested scoping is simply one of the casualties of a
> non-declarative language.

Well, this is not accurate, as you can have 'infinitely-nested
scoping' in python, in form of nested functions. For example, you can
use map(lambda x: , list_of_x), and you will have your
isolated scopes. Although due to lambdas supporting only expressions,
following this style leads to awkward and complicated code (and/or
instead if, map instead for, and so on).


-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scope of function parameters (take two)

2011-05-30 Thread Daniel Kluev
On Tue, May 31, 2011 at 12:30 PM, Terry Reedy  wrote:
> Again, go back and reread what I and other wrote. I believe that you are, in
> part, hypnotized by the work 'variable'. Can you define the word? There are
> 10 to 20 possible variations, and yours is probably wrong for Python.

On a sidenote, I wonder what is the reason to keep word 'variable' in
python documentation at all. I believe word 'name' represents concept
better, and those, who come from other languages, would be less likely
to associate wrong definitions with it.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scope of function parameters (take two)

2011-05-30 Thread Daniel Kluev
On Tue, May 31, 2011 at 11:28 AM, Henry Olders  wrote:
> What I would like is that the variables which are included in the function 
> definition's parameter list, would be always treated as local to that function

You still mis-reading docs and explanations you received from the list.
Let me try again.

First, there are objects and names. Calling either of them as
'variables' is leading to this mis-understanding. Name refers to some
object. Object may be referenced by several names or none.

Second, when you declare function `def somefunc(a, b='c')` a and b are
both local to this function. Even if there are some global a and b,
they are 'masked' in somefunc scope.
Docs portion you cited refer to other situation, when there is no
clear indicator of 'locality', like this:

def somefunc():
 print a

In this - and only in this - case a is considered global.

Third, when you do function call like somefunc(obj1, obj2) it uses
call-by-sharing model. It means that it assigns exactly same object,
that was referenced by obj1, to name a. So both obj1 and _local_ a
reference same object. Therefore when you modify this object, you can
see that obj1 and a both changed (because, in fact, obj1 and a are
just PyObject*, and point to exactly same thing, which changed).

However, if you re-assign local a or global obj1 to other object,
other name will keep referencing old object:

obj1 = []

def somefunc(a):
 a.append(1) # 'a' references to the list, which is referenced by
obj1, and calls append method of this list, which modifies itself in
place
 global obj1
 obj1 = [] # 'a' still references to original list, which is [1]
now, it have no relation to obj1 at all

somefunc(obj1)

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scope of function parameters

2011-05-30 Thread Daniel Kluev
On Mon, May 30, 2011 at 6:12 PM, Laurent Claessens  wrote:
> Could you give an example of an object that has no name ? I've missed
> something ...

>>> object()


-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: GIL in alternative implementations

2011-05-27 Thread Daniel Kluev
> So I'd like to know: how do these other implementations handle concurrency
> matters for their primitive types, and prevent them from getting corrupted
> in multithreaded programs (if they do) ? I'm not only thinking about python
> types, but also primitive containers and types used in .Net and Java VMs,
> which aren't atomic elements either at an assembly-level point of view.

Well, they definitely have some shortcomings:

test.py:

from threading import Thread
class X(object):
pass
obj = X()
obj.x = 0

def f(*args):
   for i in range(1):
   obj.x += 1

threads = []
for i in range(100):
t = Thread(target=f)
threads.append(t)
t.start()

for t in threads:
while t.isAlive():
t.join(1)

print(obj.x)

> python test.py
100
> pypy test.py
100
> jython-2.5 test.py
19217
> ipy test.py
59040

Not that this thing is reasonable to do in real code, but cpython and
other implementations with GIL at least give you some safety margin.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why did Quora choose Python for its development?

2011-05-26 Thread Daniel Kluev
On Wed, May 25, 2011 at 3:10 AM, Octavian Rasnita  wrote:
>> Once again. Suppose we have array of key-value pairs (two-dimensional
>> array),
>
> This is a forced example to fit the way Python can do it with a clean syntax, 
> but I don't think there are cases in which somebody wants to create 
> hashes/dictionaries where the key is not a plain string but an array.
>
> This is not a rare case, but a case that probably nobody needs, ever.

This is far more popular case than converting flat lists into dicts in
Python world. In fact, I *never* had need to convert flat list instead
of properly structured one. Thats why we have both lists and tuples,
after all.
Sure, since perl does not support it at all, perl programmers do not
use it and resort to idea of "guess which values are keys by index"
due to lack of better approach, with need of obscure "=>"
pseudo-syntax to cover it up.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why did Quora choose Python for its development?

2011-05-24 Thread Daniel Kluev
On Tue, May 24, 2011 at 5:00 PM, Octavian Rasnita  wrote:
> And you are telling that in Perl should be used an even more complicated and
> ugly syntax just for beeing the same as in Python just for showing that I am
> wrong, but I was comparing just the shortness and cleraness of the code.
>
> So, again, in Perl is just:
>
> %d = @l;

Once again. Suppose we have array of key-value pairs (two-dimensional
array), `l`. In python, converting it to dict is as simple as d =
dict(l). In perl, %d = @l; produces meaningless value. Following your
logic, this means that perl has ugly syntax.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Daniel Kluev
On Mon, May 23, 2011 at 10:10 PM, Octavian Rasnita  wrote:
> is not so nice as
>
> $d = @a;

It is 'not so nice' only in your perception. Python clearly defines
dict as container of (key, value) pairs, and therefore its constructor
expects such pairs. Adding unjustified arbitrary ways to guess such
pairs out of linear list is exactly what is being bashed here. Is is
considered to be wrong and bad.

Moreover, you are comparing apples to oranges here, and then
complaining that apples somehow turned out to be not oranges.
If we take python way of defining dicts and check it in perl, we find
that it is not supported, so obviously perl is non-intuitive and does
not support clear and easy way of defining hashes from list of
key-value pairs:

@l = ([1, 2], [3, 4],);
%d = @l;
for $k ( keys %d ) { print "$k\n"; }

which outputs single ARRAY(0x804e158) instead of proper 1, 3, as it
does in python:

>>> dict([[1,2], [3,4]]).keys()
[1, 3]

This is yet another example that you are just trolling here, making
silly and unbacked claims, and ignoring any valid arguments you
receive.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6 and timezones

2011-05-23 Thread Daniel Kluev
On Mon, May 23, 2011 at 10:56 PM, loial  wrote:
> Thanks...but being a python newbie I am struggling to understand how
> to do this.
>
> How can I use tzinfo to do the equivalent of what I do in Java, which
> is  :
>
>TimeZone tz1 = TimeZone.getDefault();
>
>long localOffset = tz1.getOffset(date.getTime());
>
>TimeZone tz2 = TimeZone.getTimeZone("EST");
>
>long remoteOffset = tz2.getOffset(date.getTime());
>

>>> from pytz import timezone, FixedOffset
>>> import time
>>> from datetime import datetime
>>> local_tz = FixedOffset(-time.timezone/60)

time.timezone returns local timezone in seconds and negative sign.
FixedOffset converts it into tzinfo object.

>>> now = datetime.now()
>>> local_tz.utcoffset(now)
datetime.timedelta(0, 36000)

utcoffset() returns timedelta object as offset. It requires datetime
object as first parameter due to weird API of base tzinfo class, but
it is not used in calculation, and you can pass any other object,
including None instead, like `local_tz.utcoffset(None)`

>>> remote_tz = timezone("EST")
>>> remote_tz.utcoffset(now)
datetime.timedelta(-1, 68400)

You can add or substract these timedelta objects directly from
datetime objects or use astimezone():

>>> now = datetime.now(local_tz)
>>> now
datetime.datetime(2011, 5, 23, 22, 41, 48, 398685, tzinfo=pytz.FixedOffset(600))
>>> now.astimezone(remote_tz)
datetime.datetime(2011, 5, 23, 7, 41, 48, 398685, tzinfo=)


-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Daniel Kluev
On Mon, May 23, 2011 at 10:17 PM, Octavian Rasnita  wrote:
> From: "Daniel Kluev" 
> Aha, so with other words that ORM doesn't have that feature.
> DBIX::Class also use the DateTime module, but it can use it directly,
> without needing to write more code for that, and it can also return
> localized dates.

Once again. ORMs return _python builtin type_. Localization is not
their responsibility, and plugging it there is code bloat, rather than
feature. Sure you may ask ORM to handle JSONRPC requests on its own,
but ORM responsibility is to map RDBMS features to language objects.
All good python packages limit their functionality to specific field,
so you could choose one you prefer for each different task
independently.

> without needing to load the DateTime module manually and to initialize the 
> DateTime object manually...

This is basically stating that you didn't read the code I posted.
Where did you ever find "initialize the DateTime object manually"?
Sorry, but its pointless to discuss anything if you don't want to even
read properly examples you receive.


-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6 and timezones

2011-05-23 Thread Daniel Kluev
On Mon, May 23, 2011 at 9:32 PM, loial  wrote:
> Does python have an equivalent of the java Timezone object?
>
> I need to be able to get offsets for timezones (only U.S. time zones
> at the moment)

Depends on what exactly do you want. If you need to convert timezone
name into current offset, you should use [1] or [2].
If you just need to handle known offsets for datetime objects, there
is tzinfo class in datetime module, [3].


[1] http://pypi.python.org/pypi/PosixTimeZone/0.9.4
[2] http://pypi.python.org/pypi/pytz/2011g
[3] http://docs.python.org/library/datetime.html#tzinfo-objects

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Daniel Kluev
On Mon, May 23, 2011 at 8:41 PM, Octavian Rasnita  wrote:
> From: "Daniel Kluev" 
> As I said, that ORM is not able to do those SQL constructs without using
> literal SQL code, but only Python variables and data structures...
> An ORM is usually prefered exactly because it doesn't force the programmer
> to concatenate strings for generating the SQL code, but he/she can use just
> standard Perl/Python code.
> Or this is possible in another way without using SQL code?

Did you actually read the code? SQL there is debug output of
SQLAlchemy for python code `Session.query(Test).from_self().all()`, I
left it there to just show you that it emits subquery to RDBMS.
All code in REPL is prefixed by `>>> `. Other lines are just output.

> Can it also set the current locale, for example romanian, and print the name 
> of the current month?
> ...something like t1.date.set_locale('ro').month_name?

There is separate module for date localization. You can pass datetime
object to it and it will give you needed value.

> The ones that bash other languages on the mailing list for their prefered 
> language should provide good comparisons and not just make false statements

That would be valid if I would 'bash other languages', but I just
responded to your claim that Perl has advanced modules which are not
available for Python, esp. in web frameworks, as I find it one of
areas where Python shines most.
Sure Python has drawbacks, esp. its performance and poor threads
support (GIL), but flexibility and modules of all flavors and types
are not among them. Introduction of parameter annotations should make
these modules even greater, once python 3.x is widely adopted.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Daniel Kluev
On Mon, May 23, 2011 at 7:49 PM, Octavian Rasnita  wrote:
> That is not an array, but a list. An array has a name and we can't do
> something like the following simple statement in Python:
>
> l = (1, 2)
> d = dict(l)

> An array has a name
What?
In python there is no difference whether your object has any names
mapped to it or not. Its all the same, and object itself does not even
know.
Moreover, (1, 2) is tuple rather than 'array'. If you mean array as
implemented as array, then list is what you want. If you mean array
literally, there is special type 'array' somewhere in stdlib.

As for "can't do":

>>> a = [1,2]
>>> dict([a])
{1: 2}
>>> a = (1,2)
>>> dict([a])
{1: 2}


-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Daniel Kluev
On Mon, May 23, 2011 at 5:06 PM, Octavian Rasnita  wrote:
> There are more, but a single eloquent feature is the possibility of
> interpreting variables in strings which cannot be done so nice in Python.

I've should probably mentioned it earlier, but I'm not Perl expert,
not following its development and can't be bothered to read its docs.
Could you please provide examples of features you mention with
expected result, so I could suggest reasonable Python analogue?

> This is false. Explicit in this case means to write code in 2 places for
> doing a certain thing, and maintaining means changing the code in 2 places,
> which is harder and prone to errors.

Not sure what do you mean by 'write code in 2 places'. All mapping
code is located in routes config, including all needed args
validation.
But if you want to couple it with controller code, there, as I said,
are numerous ways to do it. You can even do something like this:

class SomeController(BaseController):
...
@map(conditions=dict(method='GET'))
def some_method(self, arg1:int, arg2:str):
 ...

so it would be called via /somecontroller/some-method/1/blabla with
trivial decorator.

> (unless in Pylons/Pyramid can be also defined chained mappings and mappings
> based on regular expressions).

Not sure what do you mean by "based on regular expressions". Routes
paths ARE regular expressions. Conditions are regexes too.

As for chained mappings - no idea, never had the need in such thing.

> Yes, the single difference is that Catalyst supports all of them, and it
> also supports using any templating system, and any ORM and any form
> processor, while some of the Python web frameworks don't support absolutely
> everything and you need to abandon some preferred modules for beeing able to
> use some other modules which are supported.

Pyramid and Pylons let you use pretty much any templating package and
ORM as well. There is nothing in them that would block such modules.

> I've checked the documentation for some of them and I've seen that most of
> them don't support sub-selects and some of them require using plain SQL code
> in their construct for more complex queries.
> Please tell me which of them supports sub-selects, and are able to return
> objects for date and datetime fields that have methods for beeing able to
> print just the year or day, or the months names in the specified locale
> because it would be useful.

Python has builtin type for DateTime, and SQLAlchemy, for example,
returns exactly that:

#> python
Python 2.7.1 (r271:86832, May 17 2011, 19:31:41)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from sadt import Test, Session
>>> import datetime
>>> Test(1)

>>> Test(2)

>>> t1 = Session.query(Test).filter(Test.val == 1).one()
>>> t1

>>> t1.date
datetime.datetime(2011, 5, 23, 18, 53, 39, 459054)
>>> t1.date.year
2011
>>> t1.date.month
5
>>> print Session.query(Test).filter(Test.date == datetime.datetime(2011, 5, 
>>> 23, 18, 53, 39, 459054)).one()

>>> print Session.query(Test).filter(Test.date > datetime.date(2010, 1, 
>>> 1)).all()
[, ]

sadt sources here if interesting: http://pastebin.ca/2067372

So as you see, datetime is not only returned properly, but you can
also do queries with either date or datetime values, including
comparison and range.

Subqueries are fully supported too:
>>> ...
>>> Session.query(Test).from_self().all()
2011-05-23 19:07:02,662 INFO sqlalchemy.engine.base.Engine.0x...552c
SELECT anon_1.test_id AS anon_1_test_id, anon_1.test_val AS
anon_1_test_val, anon_1.test_date AS anon_1_test_date
FROM (SELECT test.id AS test_id, test.val AS test_val, test.date AS test_date
FROM test) AS anon_1
2011-05-23 19:07:02,662 INFO sqlalchemy.engine.base.Engine.0x...552c ()
[, , , , ]

This is most trivial example of subqueries, since I'm too lazy to
produce proper tables to demonstrate it, but SQLAlchemy has very good
subquery support, as its typical way to deal with one-to-many
relations (but it does support other loading strategies as well,
including inner/outer joins or lazy loading).

> it can do but DBIx::Class cannot, because otherwise it would be very simple
> for anyone to just say "go to read the documentation and see how great it
> is".

But "go to read the docs" argument works both ways - I have zero
knowledge of DBIx::Class, so obviously I cannot say what features it
lacks compared to SQLA.
However this is what I wanted to highlight - you cannot simply state
that "Perl offers more advanced modules and libraries which are not
available for Python" if you don't have reasonable experience with
according Python modules.


-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why did Quora choose Python for its development?

2011-05-22 Thread Daniel Kluev
On Sun, May 22, 2011 at 11:47 PM, Octavian Rasnita  wrote:
> From: "Daniel Kluev" 
> I am talking about that flexibility which was criticized in the previous 
> messages telling that this flexibility allows any programmer to use his own 
> way.
> Perl doesn't force anyone to indent the code, don't force the programmer to 
> define a hash element before using it, allow the programmer to interpret the 
> variables in strings directly. These things should be not used always, but if 
> in some cases if the programmer wants to use them, he can use them with no 
> problems. And this means flexibility.

This is syntax-level flexibility, which, IMHO, does not affect
'advanceness' of modules at all. At language level, python is far more
flexible than perl with its magic methods and hooks, allowing to
overload any underlying language principles and protocols.

> First, this is a bad style of mapping urls, because this list must be 
> maintained every time the programmer changes something in a controller that 
> makes the app need to use other urls.

Explicit is better than implicit. One of reasons why I chose
Pylons/Pyramid as my standard toolkit is that it allowed me to define
mappers in any way I needed them to.
If you want automatically defined mappers, there are lots of other
python frameworks and modules which do exactly that. Moreover, even
Routes itself (module, which does url mapping in Pylons) allows you to
use automated mappers, via :controller/:action tokens. It allows
pretty much everything you listed as 'features' of catalyst mappings.
If you prefer to stuff routing logic into controllers and have default
routing based on controllers and method names, you can use TurboGears
framework, which has exactly that mindset, or you can use its mapping
modules in Pyramid application.

> The module DBIx::Class which is used usually as an ORM can create the class 
> files for all the tables from a database (MySQL, Oracle, PostgreSQL, SQLite, 
> MS SQL, etc), and it can be used to search using unions, sub-selects, can 
> define views at ORM level, can accept to insert different types of objects 
> like DateTime objects and can also return those type of objects, and many 
> other things, and most of the things it can do can be done without using SQL 
> code at all, but only standard Perl code and Perl data structures.

There are lots of Python modules which do exactly this and much more.
SQLAlchemy, SQLObject, Web2Py's DAL, and so on. They are integrated
into frameworks by default.

> HTML::FormFu form processor is one of the most used form processors in 
> Catalyst applications and it can generate and parse forms created directly in 
> the code of the application, or as external configuration files defined using 
> JSON, or YAML, or Apache configuration style, or Perl data structures, or 
> XML...
> The forms defined are very easy to create and the elements from those forms, 
> for example the list of elements in a combo box can be taken directly from a 
> database by specifying just a few configuration elements. The results of a 
> form submit can be also inserted in a database using a connector with 
> DBIx::Class without specifying any database table column name in the 
> programming code, and for doing this are required just a few lines of code 
> that checks if the $form->submitted_and_valid() and that does the redirection 
> after the submit, the insertion in the database requiring just:

Once again, there are dozens of such modules in python. FormAlchemy
integrates directly with SQLAlchemy, for example, and does all form
generation, parsing, validation, and instance updating/inserting for
you.

> Yes, for web apps I have seen more things which can be done much better in 
> Perl, much easier and clear, with less code, and not because the programmer 
> needs to do not-recommended tricks for shortening the code, but because there 
> are very many modules on CPAN that do the hard work.

I doubt you had enough experience with python frameworks like
Pyramid/Pylons or Web2Py. They have all features you listed, and code
is as trivial and clean, as it could ever be. Its surprising that you
present trivial ORM as 'advanced modules and libraries which are not
available for Python', while in fact it have been done long time ago
and in several flavors.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Abandoning Python

2011-05-22 Thread Daniel Kluev
On Mon, May 23, 2011 at 4:33 AM, John Lee  wrote:
> Pylint?  Does it provide some kind of guessed-at-type that has been integrated
> with IDEs?

WingIDE Pro has both Pylint integration and advanced type-guessing.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why did Quora choose Python for its development?

2011-05-22 Thread Daniel Kluev
On Sun, May 22, 2011 at 6:44 PM, Octavian Rasnita  wrote:
> Because of its flexibility, Perl offers more advanced modules and libraries 
> which are not available for Python.

What 'flexibility' are you talking about? This seem to be very biased
statement, based on lack of according python experience.

There are many python web frameworks which allow you to use w/e
interfaces, template languages and ORMs you want - Pyramid/Pylons is
good example.
'Very powerful' and 'great' are 'very useless' descriptions of these
modules. Please, show us what exactly is so 'advanced' about them
which cannot be done in python.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Abandoning Python

2011-05-21 Thread Daniel Kluev
On Sun, May 22, 2011 at 12:25 PM, Daniel Kluev  wrote:
> According to all language popularity indexes [1-10], C# and

Forgot to include references, although everyone probably already knows them,

[1] https://www.ohloh.net/languages?query=&sort=projects
[2] http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
[3] http://libresoft.es/debian-counting/lenny/index.php?menu=Statistics
[4] http://lang-index.sourceforge.net/
[5] http://langpop.com/
and so on

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Abandoning Python

2011-05-21 Thread Daniel Kluev
On Sun, May 22, 2011 at 2:49 AM, John J Lee  wrote:
> Here's my wishlist (not really in any order):

How come pony is not listed there? Language cannot be better than
python without pony!

>  * An even larger user base, contributing more and better free and
>   commercial software.

According to all language popularity indexes [1-10], C# and
Objective-C are only languages which have any chance to fulfill these
requirements, but they arguably less flexible than python and have
copyright/patent complications.
As there is rather heavy inertia in software development community,
expecting some language to acquire "even larger user base" is
hopeless.

Also, most of these complaints could be solved by using correct python
dialect for particular task - RPython, Cython and so on.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overuse of try/except/else?

2011-05-21 Thread Daniel Kluev
On Tue, May 10, 2011 at 11:40 AM, Kyle T. Jones
 wrote:
>
> It has been hard for me to determine what would constitute overuse.
>

Good example of abuse is catching KeyboardInterrupt or SystemExit
inside some library code. PycURL does it, and its truly annoying.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a set into list

2011-05-15 Thread Daniel Kluev
> Both solutions seem to be equivalent in that concerns the number of needed 
> loop runs, but this two-step operation might require one less loop over list1.
> The set&set solution, in contrary, might require one loop while transforming 
> to a set and another one for the & operation.

python -m timeit -s "l1 = range(1, 1); l2 = range(5000, 15000)"
"l3 = list(set(l1) & set(l2))"
100 loops, best of 3: 2.19 msec per loop

python -m timeit -s "l1 = range(1, 1); l2 = range(5000, 15000)"
"s=set(l2); l3 = [i for i in l1 if i in s]"
100 loops, best of 3: 2.45 msec per loop

python -m timeit -s "l1 = range(1, 10); l2 = range(5, 15)"
"l3 = list(set(l1) & set(l2))"
10 loops, best of 3: 28 msec per loop

python -m timeit -s "l1 = range(1, 10); l2 = range(5, 15)"
"s=set(l2); l3 = [i for i in l1 if i in s]"
10 loops, best of 3: 28.1 msec per loop

So even with conversion back into list set&set is still marginally faster.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: obviscating python code for distribution

2011-05-15 Thread Daniel Kluev
On Mon, May 16, 2011 at 1:04 PM, Littlefield, Tyler  wrote:
> Hello all:
> Finally, is there a good way to accomplish this? I know that I can make .pyc
> files, but those can be disassembled very very easily with the disassembler
> and shipping these still means that the person needs the modules that are
> used. Is there another way to go about this?

No, there is no way to prevent users from getting access to raw python
sources. By its nature and design, python is not meant to be used this
way, and even obfuscation would not harm readability much.
However, you can write all parts you want to hide in C/C++/Cython and
distribute them as .so/.dll

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threads with gtk gui problem

2011-05-15 Thread Daniel Kluev
You can also use multiprocessing module instead of threads. Use pipe
and gobject.idle_add(somefunc) to process data from other thread.


-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.2 Vectors.py module

2011-05-15 Thread Daniel Kluev
On Sun, May 15, 2011 at 8:15 PM, Algis Kabaila  wrote:
> Hi All,
>
> I would really appreciate any comments and suggestions for the Vectors.py
> module, which can be downloaded from

- If you intend to provide it as general-purpose vector module for
other people to use, it would be better if you pack it in separate
package and upload to PyPI.
  You can find good tutorial on packaging here:
http://diveintopython3.org/packaging.html

- NumPy/SciPy has pretty fair support for vectors. Would be good if
you pointed out the differences to begin with.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How best to convert a string "list" to a python list

2011-05-14 Thread Daniel Kluev
On Sat, May 14, 2011 at 7:41 PM, Nobody  wrote:
> to use a regular expression to match everything up to the next delimiter,
> and do this in a loop to extract the individual items.

re.findall() should let you match all items at once, without loop.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do directly imported variables behave differently than those attached to imported module?

2011-05-03 Thread Daniel Kluev
On Wed, May 4, 2011 at 6:23 AM, Dun Peal  wrote:
> P.S. now I have to ask: is there a symbolic reference in Python, i.e.
> a name foo that points to "whatever bar.baz is pointing at"?

Well, you could easily simulate that with proxy object,
class SymbolicReference(object):
def __init__(self, ns, name):
self.__ns = ns
self.__name = name

def __get(self):
return self.__ns[self.__name]

def __getattribute__(self, attr):
try:
return object.__getattribute__(self, attr)
except:
return self.__get().__getattribute__(attr)

def __repr__(self):
return self.__get().__repr__()

def __str__(self):
return self.__get().__str__()

>>> a = 1
>>> b = SymbolicReference(globals(), 'a')
>>> b
1
>>> a = 10
>>> b
10


-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do directly imported variables behave differently than those attached to imported module?

2011-05-03 Thread Daniel Kluev
On Wed, May 4, 2011 at 3:31 AM, Dun Peal  wrote:
> Apparently, the `var` we imported from `foo` never got set, but
> `foo.var` on the imported `foo` - did. Why?

Because all names are references to some values, not other names (in
CPython, it means all names are PyObject*, and point directly to the
objects, not other pointers)

When you do `from foo import bar` it assigns globals()['bar'] of
current module to reference same value as `foo.bar`. Its now local
namespace name, not `foo` namespace, and therefore functions in `foo`
cannot modify this namespace.

Since ints are immutable, when you do `var = 1` you create new object
of type int, and re-assign `var` name to point to new object.

`foo.var`, on other hand, is a way to access `foo`'s own namespace, so
its exactly same name as globals()['var'] of `foo`.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] Comparing VCS tools (was ""Development tools and practices for Pythonistas")

2011-04-29 Thread Daniel Kluev
We were looking for some simple integrated SCM, issue tracker and wiki
in our university for software design and software testing courses,
and fossil seems to be perfect match, thanks for sharing.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: use of index (beginner's question)

2011-04-28 Thread Daniel Kluev
On Thu, Apr 28, 2011 at 11:42 AM, Rusty Scalf  wrote:
> list1 = ['pig', 'horse', 'moose']
> list2 =  ['62327', '49123', '79115']
> n = 2
> s2 = "list" + `n`
> a = s2[list1.index('horse')]
> print a
>
>  -does not work

While advices above are indeed right way to go in your case, there is
a way to get variable by its name.

>>> list2 = ['62327', '49123', '79115']
>>> n = 2
>>> s2 = "list{0}".format(n)
>>> print s2
list2
>>> print locals()[s2]
['62327', '49123', '79115']
>>> print locals()[s2][0]
62327

But generally if you need to do that, you would be better with
re-design of your data/architecture.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] VCS tools

2011-04-28 Thread Daniel Kluev
On Fri, Apr 29, 2011 at 8:50 AM, Ben Finney  wrote:
> Martin Schöön  writes:
>
> I seriously recommend anyone looking for a modern VCS to give Bazaar a
> decent trial. It's the one I've found newcomers learn most easily, and
> it's astoundingly flexible as one's needs with it grow.
>

When I was deciding what DVCS I should use for personal projects, Bzr
was first thing I tried. It was quite uncomfortable experience after
svn, esp. with branches and merges, working not the way I was
expecting it to.
Mercurial, on the contrary, did exactly what I was expecting it to,
and was overall very easy to learn.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function __defaults__

2011-04-24 Thread Daniel Kluev
On Mon, Apr 25, 2011 at 8:21 AM, Ken Seehart  wrote:
> Good point, Benjamin.  I didn't think of testing on Jython before
> answering.  For practical purposes it's a really good idea to test obscure
> features against all potential target platforms.
>
> In this case, I would argue that Benjamin's test demonstrates a bug in
> Jython.

It doesn't. __defaults__ was added in 3.x (and it is documented).
Prior to that, in 2.x, there was func_defaults.

Jython is not in 3.x yet, so you should not expect 3.x features there.
As for func_defaults, its there and supported as documented:

Jython 2.5.1+ (Release_2_5_1:exported, Mar 21 2010, 01:00:17)
[Java HotSpot(TM) Server VM (Sun Microsystems Inc.)] on java1.6.0_22
Type "help", "copyright", "credits" or "license" for more information.
>>> def test(a=123):
... return a
...
>>> test()
123
>>> test.func_defaults
(123,)
>>> test.func_defaults = (456,)
>>> test()
456

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function __defaults__

2011-04-24 Thread Daniel Kluev
http://docs.python.org/dev/reference/datamodel.html
Callable types
...
Special attributes:
...
__defaults__A tuple containing default argument values for those
arguments that have defaults, or None if no arguments have a default
value   Writable

I don't see any 'implementation detail' mark there, and 'Writable'
IMHO means it can be used.

On Mon, Apr 25, 2011 at 4:02 AM, Benjamin Kaplan
 wrote:
> Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54)

In 2.x it was func_defaults (http://docs.python.org/reference/datamodel.html)
__defaults__ is 3.x feature

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When is PEP necessary?

2011-04-23 Thread Daniel Kluev
On Sat, Apr 23, 2011 at 11:16 PM, Disc Magnet  wrote:
> Is PEP necessary to add a new package to the standard library?
> *skip*

Don't forget that Python is not limited to CPython. Other
implementations need these PEPs to provide compliant packages.
While its not that important for pure-python modules, anything tied to
C-API better be documented, or it becomes a nightmare to keep
non-CPython version having identical interface.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Argument count mismatch

2011-04-22 Thread Daniel Kluev
On Fri, Apr 22, 2011 at 12:43 PM, Steven D'Aprano
 wrote:
> It looks to me like this function relies on no fewer than three global
> variables, two that you read from and one which you write to:
>
> c
> Session
> MSPResponse
>
> This is almost certainly poor design. Using global state is almost always
> harmful and should be avoided.

Looks like its something similar to Pylons web framework. While
generally globals vars are indeed bad, in this case they are
specifically provided by framework to be used this way.
They are 'thread-local' rather than global, and usually cause no harm,
since framework guarantees that these instances are bound to context
of this particular http request.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there a difference between one line and many lines

2011-04-21 Thread Daniel Kluev
On Thu, Apr 21, 2011 at 8:38 PM, vino19  wrote:
> Hello, I'm a newbie.
> What's the defference between
>*skip*

What is version of CPython?
In 2.7.1 and 3.1.3 both versions return True, and moreover, are
compiled to identical bytecode.

>>> def test1():
... a=-6; b=-6; c = a is b
... return c
>>> def test3():
... a=-6
... b=-6
... c = a is b
... return c
>>> test1()
True
>>> test3()
True
>>> dis.dis(test1)
  2   0 LOAD_CONST   1 (-6)
  3 STORE_FAST   0 (a)
  6 LOAD_CONST   1 (-6)
  9 STORE_FAST   1 (b)
 12 LOAD_FAST0 (a)
 15 LOAD_FAST1 (b)
 18 COMPARE_OP   8 (is)
 21 STORE_FAST   2 (c)
  3  24 LOAD_FAST2 (c)
 27 RETURN_VALUE
>>> dis.dis(test3)
  2   0 LOAD_CONST   1 (-6)
  3 STORE_FAST   0 (a)
  3   6 LOAD_CONST   1 (-6)
  9 STORE_FAST   1 (b)
  4  12 LOAD_FAST0 (a)
 15 LOAD_FAST1 (b)
 18 COMPARE_OP   8 (is)
 21 STORE_FAST   2 (c)
  5  24 LOAD_FAST2 (c)
 27 RETURN_VALUE

So AFAIK, there is no difference for interpreter itself, its purely
syntactic, and is compiled to exactly same bytecode.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can you advice a Python library to query a lan subnet with SNMP and collect MAC addresses of nodes?

2011-04-18 Thread Daniel Kluev
Isn't it better to use subprocess.Popen and read stdout/stderr
directly? Should be much more convenient than temporary files.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re: Equivalent code to the bool() built-in function

2011-04-17 Thread Daniel Kluev
On Mon, Apr 18, 2011 at 12:46 PM, Dave Angel  wrote:
> He didn't say that the function will call the bool() type (constructor), but
> that it will use the bool type;

Actually, he did say exactly that
> Any boolean expression is going to be _calling the built-in ‘bool’ type 
> constructor_
(underscores are mine)

>The one that may not is the function bool().
Its not function, its type. There is no wrapper, bool(x) is direct
constructor call.

> Once bool has been reassigned, calling it may not return True or False any 
> more.
Not sure what did you want to show with this example. You just
assigned name in locals() namespace. Boolean type itself didn't change
because of that and would still call PyObject_IsTrue() and return
according constant. Sure, python allows to change namespaces in very
flexible way, but we are talking about specific objects (PyBool_Type)
rather than pointers to them.

> in other words, it will return True or False.
Well, his code explicitly returns True or False, so this was not doubted.

Although I agree with Ben that this doesn't have any practical
meaning. bool() is more readable and implementation-independent way to
do explicit casting to boolean than the hack in OP.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Equivalent code to the bool() built-in function

2011-04-17 Thread Daniel Kluev
On Sun, Apr 17, 2011 at 8:38 AM, Ben Finney  wrote:
> It won't look up the *name* ‘bool’, but it will use that object. Any
> boolean expression is going to be calling the built-in ‘bool’ type
> constructor.
>
> So the answer to the OP's question is no: the function isn't equivalent
> to the type, because the OP's ‘bool_equivalent’ function necessarily
> uses the built-in ‘bool’ type, while the reverse is not true.

Actually, as I was curious myself, I've checked sources and found that
`True if x else False` will _not_ call bool(), it calls
PyObject_IsTrue() pretty much directly.
>>> import dis
>>> def bool2(x):
... return True if x else False
...
>>> dis.dis(bool2)
  2   0 LOAD_FAST0 (x)
  3 POP_JUMP_IF_FALSE   10
  6 LOAD_GLOBAL  0 (True)
  9 RETURN_VALUE
>>   10 LOAD_GLOBAL  1 (False)
 13 RETURN_VALUE


case POP_JUMP_IF_FALSE:
w = POP();
if (w == Py_True) {
Py_DECREF(w);
goto fast_next_opcode;
}
if (w == Py_False) {
Py_DECREF(w);
JUMPTO(oparg);
goto fast_next_opcode;
}
err = PyObject_IsTrue(w);
Py_DECREF(w);
if (err > 0)
err = 0;
else if (err == 0)
JUMPTO(oparg);
else
break;
continue;

So technically these implementations are equivalent besides the fact
that bool() is type rather than function.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Equivalent code to the bool() built-in function

2011-04-17 Thread Daniel Kluev
On Sun, Apr 17, 2011 at 7:38 PM, candide  wrote:
> I could't imagine a builtin function having a so trivial implementation.

As it was pointed out, its not function, its type,
SETBUILTIN("bool",  &PyBool_Type);

While its __new__ is indeed trivial (in essence, it just calls
PyObject_IsTrue), it also provides needed comparison ops, repr and
other magic methods for the type.
You can check Objects/boolobject.c in python repository if its
implementation is interesting for you.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE/text-editor

2011-04-16 Thread Daniel Kluev
On Sat, Apr 16, 2011 at 4:43 PM, Alec Taylor  wrote:
> Thanks, but non of the IDEs so far suggested have an embedded python
> interpreter AND tabs... a few of the editors (such as Editra) have
> really nice interfaces, however are missing the embedded
> interpreter... emacs having the opposite problem, missing tabs (also,
> selecting text with my mouse is something I do often).
>
> Please continue your recommendations.

WingIDE has all that and much more, if you are willing to consider
non-free IDE.
Its multi-threading debugger definitely worth the cost of Pro version for me.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What people are using to access this mailing list

2010-11-03 Thread Daniel Kluev
I use gmail with according filters and labels, so each mailing list has its
own label and is removed from inbox.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would you recommend python as a first programming language?

2010-11-01 Thread Daniel Kluev
>
> I was thinking of recommending this to a friend but what do you all think?
>

Python is great language to learn programming.
I've heard MIT switched from Scheme to Python as introductory language for
their students.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Discarding STDERR generated during subprocess.popen

2010-08-23 Thread Daniel Kluev
On Tue, Aug 24, 2010 at 4:38 AM, Leon Derczynski wrote:

> Hi,
>
> I would like to run an external program, and discard anything written
> to stderr during its execution, capturing only stdout. My code
> currently looks like:
>
> def blaheta_tag(filename):
>blaheta_dir = '/home/leon/signal_annotation/parsers/blaheta/'
>process = subprocess.Popen([blaheta_dir + 'exec/funcTag',
> blaheta_dir + 'data/', filename], cwd=blaheta_dir,
> stdout=subprocess.PIPE)
>process.wait()
>return process.communicate()[0]
>
> This returns stdout, and stderr ends up printing to the console. How
> can I disregard anything sent to stderr such that it doesn't appear on
> the console?
>

Just add `stderr=subprocess.PIPE` keyword in the Popen call.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterative vs. Recursive coding

2010-08-19 Thread Daniel Kluev
On Fri, Aug 20, 2010 at 8:12 AM, Baba  wrote:

> Level: Beginner
>
> exercise source:
>
> http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset3.pdf
>
> I am looking at the first problem in the above assignment. The
> assignemnt deals, amongst others, with the ideas of iterative vs.
> recursive coding approaches and i was wondering what are the
> advantages of each and how to best chose between both options?
>
>
With Python, I'd avoid using recursions unless it is absolutely needed /
much simpler than iteration and depth is known in advance, and not exceeds
the limit.
Reason is that Python does not optimize recursion calls, and even tail
recursions get own stack frame on each call.
It is more expensive than iteration and risks to exceed max recursion depth.


part 2 recursive approach:
>
>
> def countSubStringMatchRecursive(target,key):
>counter=0
>fsi=0 #fsi=find string index
>if len(key)==len(target):   #base case
>  if key==target:
>   counter+=1
>elif len(key)while fsifsi=target.find(key,fsi)
>if fsi!=-1:
>   counter+=1
>else:
>break
>fsi=fsi+1
>else:
>print 'key is longer than target...'
>
>print '%s is %d times in the target string' %(key,counter)
>
>
> countSubStringMatchRecursive("atgacatgcacaagtatgcat","atgacatgcacaagtatgcatatgc")
>

Maybe I'm missing something, but this one seems to be iterative too.
Recursive is one which calls itself, like

def countSubString(haystack, needle):
 def checkMatch(haystack, needle):
  if not needle:
  return True
  elif not haystack:
  return False
  elif haystack[0] == needle[0]:
  return checkMatch(haystack[1:], needle[1:])
  else:
  return False
 return len(filter(bool, map(lambda i: checkMatch(haystack[i:], needle),
range(len(haystack)

Where checkMatch would be called recursively to match needle over particular
part of haystack.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: path to data files

2010-08-19 Thread Daniel Kluev
On Thu, Aug 19, 2010 at 9:25 PM, Daniel Fetchinson <
fetchin...@googlemail.com> wrote:

> If a python module requires a data file to run how would I reference
> this data file in the source in a way that does not depend on whether
> the module is installed system-wide, installed in $HOME/.local or is
> just placed in a directory from where the interpreter is fired up? I'd
> like to always keep the python source and the data file in the same
> directory, be it /usr/lib/python2.6/site-packages,
> $HOME/.local/lib/python2.6/site-packages or
> /arbitrary/path/to/somewhere.
>

open(os.path.join(os.path.dirname(__file__), 'foo'))

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: expression in an if statement

2010-08-18 Thread Daniel Kluev
On Thu, Aug 19, 2010 at 9:12 AM, Thomas Jollans  wrote:

> I doubt any actual Python implementation optimizes this -- how could it?
> The
> object "set" is clearly being called twice, and it happens to be called
> with
> the object "a" as a sole argument twice. What if "set" has side effects? A
> compiler could only exclude this possibility if it knew exactly what "set"
> will be at run time, which it can't.
>
> I expect that "set" and "a" have to be looked up twice, actually:
> "set(a).union(b)" might rebind either one of them. This would be considered
> a
> very rude and inappropriate thing to do, but Python usually guarantees to
> allow bad taste and behaviour.
>
>
Yep.

>>> def test():
... a = [1]
... b = [1]
... if set(a).union(b) == set(a): pass
...
>>> dis.dis(test)
  2   0 LOAD_CONST   1 (1)
  3 BUILD_LIST   1
  6 STORE_FAST   0 (a)

  3   9 LOAD_CONST   1 (1)
 12 BUILD_LIST   1
 15 STORE_FAST   1 (b)

  4  18 LOAD_GLOBAL  0 (set)
 21 LOAD_FAST0 (a)
 24 CALL_FUNCTION1
 27 LOAD_ATTR1 (union)
 30 LOAD_FAST1 (b)
 33 CALL_FUNCTION1
 36 LOAD_GLOBAL  0 (set)
 39 LOAD_FAST0 (a)
 42 CALL_FUNCTION1
 45 COMPARE_OP   2 (==)
 48 JUMP_IF_FALSE4 (to 55)
 51 POP_TOP
 52 JUMP_FORWARD 1 (to 56)
>>   55 POP_TOP
>>   56 LOAD_CONST   0 (None)
 59 RETURN_VALUE



> I might be wrong on some points here, but this is what I expect the
> expression
> (set(a).union(b) == set(a)) has to do, in any conforming implementation of
> Python. Please correct me if I'm wrong.
>

You can use dis module to let Python do compiling and explaining for you

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need to import stuff

2010-08-17 Thread Daniel Kluev
On Wed, Aug 18, 2010 at 9:40 AM, abhijeet thatte
wrote:

> Hi,
>
> Thanks for the reply. But I guess it does not support nested file paths.
> If user gives 'abcd' then I need to import "*/Do/Stuff/abcd*". Out of
> which only *"abcd" is taken run time. Do and Stuff are fixed. *
> *I got an error "*ImportError: Import by filename is not supported.". Any
> solution??
>
>
For complex importing, you can use imp module,
http://docs.python.org/library/imp.html

Like this:
module_desc = imp.find_module(name, [base_path])
module = imp.load_module(full_name, *module_desc)

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String substitution VS proper mysql escaping

2010-08-17 Thread Daniel Kluev
2010/8/18 Νίκος 

> a) I wanted to ask what is proper escaping mean and
>
>
Proper escaping means that value is wrapped in quotes properly, and quotes
and backslashes (or any other special to RDBMS symbol) are escaped with
backslashes.

why after variable page syntax has a comma
>

Comma just means its tuple.

(page) is equal to page, while (page,) is one-element tuple which contains
page:

>>> ('123')
'123'
>>> ('123',)
('123',)



> why don't my code as i have it now for string reproduction
>
> ===
> http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT
> * FROM visitors "
> ===
>
> don't reproduce the problem of actual deleting my data. I don't care
> losing it!
>
> I just want to see that happening with my own eyes!
>
>
Your script there just throws an exception for any page data, and most
likely does not run any query at all:

> 28 # open current html template and get the page ID number
> 29 #
> =
> 30 f = open( '/home/webville/public_html/' + page )
> 31
> 32 # read first line of the file
> f undefined, builtin open = , page = ['index.html', '100']
> TypeError: cannot concatenate 'str' and 'list' objects
>

Besides, using user-provided data and just concatenating it to filename like
that is definitely bad idea.
You should use os.path.join() at least.

Regarding that kind of SQL injection, typically driver will stop it to
happen when you provide 2 queries at once delimited by ';', so drop table
would not work. However its possible to issue UNION's to retrieve sensitive
data from your database.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list