Re: Dependency management in Python?

2013-01-12 Thread Thomas Bach
On Fri, Jan 11, 2013 at 06:42:18PM -0800, Adelbert Chang wrote:
 Another question - how do we then get PIP to the latest version? Or
 is it relatively easy to uninstall/reinstall PIP?

Simply do a 

$ pip install -U distribute
$ pip install -U pip

from time to time in your virtual environment.

As a side note: some versions of distribute, pip and virtualenv do
interact rather poorly on Python 3. Upgrading via easy_install:

$ easy_install -U distribute
$ easy_install -U pip

usually solves these issues.

Have fun!

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


Re: Custom alphabetical sort

2012-12-24 Thread Thomas Bach
On Mon, Dec 24, 2012 at 07:32:56AM -0800, Pander Musubi wrote:
 I would like to sort according to this order:
 
 (' ', '.', '\'', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 
 'A', 'ä', 'Ä', 'á', 'Á', 'â', 'Â', 'à', 'À', 'å', 'Å', 'b', 'B', 'c', 'C', 
 'ç', 'Ç', 'd', 'D', 'e', 'E', 'ë', 'Ë', 'é', 'É', 'ê', 'Ê', 'è', 'È', 'f', 
 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'ï', 'Ï', 'í', 'Í', 'î', 'Î', 'ì', 'Ì', 
 'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'ñ', 'N', 'Ñ', 'o', 'O', 'ö', 
 'Ö', 'ó', 'Ó', 'ô', 'Ô', 'ò', 'Ò', 'ø', 'Ø', 'p', 'P', 'q', 'Q', 'r', 'R', 
 's', 'S', 't', 'T', 'u', 'U', 'ü', 'Ü', 'ú', 'Ú', 'û', 'Û', 'ù', 'Ù', 'v', 
 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z')
 

One option is to use sorted's key parameter with an appropriate
mapping in a dictionary:

 cs = (' ', '.', '\'', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', 
 '9', 'a', 'A', 'ä', 'Ä', 'á', 'Á', 'â', 'Â', 'à', 'À', 'å', 'Å', 'b', 'B', 
 'c', 'C', 'ç', 'Ç', 'd', 'D', 'e', 'E', 'ë', 'Ë', 'é', 'É', 'ê', 'Ê', 'è', 
 'È', 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'ï', 'Ï', 'í', 'Í', 'î', 'Î', 
 'ì', 'Ì', 'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'ñ', 'N', 'Ñ', 'o', 
 'O', 'ö', 'Ö', 'ó', 'Ó', 'ô', 'Ô', 'ò', 'Ò', 'ø', 'Ø', 'p', 'P', 'q', 'Q', 
 'r', 'R', 's', 'S', 't', 'T', 'u', 'U', 'ü', 'Ü', 'ú', 'Ú', 'û', 'Û', 'ù', 
 'Ù', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z')

 d = { k: v for v, k in enumerate(cs) }

 import random

 ''.join(sorted(random.sample(cs, 20), key=d.get))
'5aAàÀåBCçËÉíÎLÖøquùx'

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


Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)

2012-12-23 Thread Thomas Bach
Hi there,

On Sun, Dec 23, 2012 at 01:42:14PM -0800, prilisa...@googlemail.com wrote:
 […] In the lower section you see, that the modules should execute
 sqls. In case It could occur that two queries occur at the same
 time.  PS: IT IS NOT A QUESTION ABOUT SQL, etc. I do not understand,
 how I could handle the part which is marked with Problemsection1 and
 Problemsection2

I actually do not understand the problem you are stating. But, did you
have a look at SQLAlchemy? If you are coping a lot with SQL it really
makes your life much easier and they also provide the necessary
mechanisms for threading.

 import HomeLog # LogHandler

Modules should be written all lower-case separated by underscores.

 # Attach Loghandler
 Loghandler = HomeLog.Logging()

Have a look at the logging module and tutorial. I don't know what is
in HomeLog.Logging, but this doesn't seem right. 

Variables defined at module level should be written all upper-case.

 # Attach SocketServer
 HomeSocketServer.HomeSocketServerStart()
 
 # Attach Scheduler
 HomeSched = HomeScheduler.HomeScheduler()
 […]
 # This is a Sample that builds 2byte Cmd and transmits it on bus
 PowerOnLamp1=Dali.send(0,0,1,80)

You do all this on the module level? These things should go into
functions with proper names or at least into a 

if __name__ == '__main__':
pass


 ###
 HomeDaliServer.py
 
 def send (self,DaliAdress,RequestType,Request,RequestValue):
 # Problemsection1:
 # Here it's getting Interesting
 # We're at the HomeDaliServer, and now I want to use QuerySqlite()
 in the file HomeDatastore.py

So, where's the problem?

# make sure not to introduce cyclic dependence here!
import home_data_store

def send (connection,DaliAdress,RequestType,Request,RequestValue):
results = home_data_store.query_sqlite(connection, …)
return results


 ###
 HomeScheduler.py
 # Problemsection2:
 # If new workerthread is started, Informations must be queried using
 QuerySlite() and also update data

So, here's a first sketch (untested):

def query():
data = do_something()
return data

def update(data):
do_something_with(data)


 HomeDatastore.py
 def QuerySqlite():
 #doing something here..
 # returning Data

Have you read the Python tutorial by the way?

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


Re: counting how often the same word appears in a txt file...But my code only prints the last line entry in the txt file

2012-12-19 Thread Thomas Bach
Hi,

just as a side-note

On Wed, Dec 19, 2012 at 02:45:13AM -0800, dgcosgr...@gmail.com wrote:
 for word in list: 
   if word in dict:
   count = dict[word]
   count += 1
   dict[word] = count
 else:
   dict[word] = 1

When you got the indentation and names right, you can restate this as

import collections
counter = collections.Counter(words)

in Python 2.7 or as

import collections
counter = collections.defaultdict(int)
for word in words:
counter[word] += 1

in Python 2.6

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


Re: Pattern-match Replace - help required

2012-12-19 Thread Thomas Bach
On Wed, Dec 19, 2012 at 02:42:26AM -0800, AT wrote:
 Hi,
 
 I am new to python and web2py framework. Need urgent help to match a
 pattern in an string and replace the matched text.
 

Well, what about str.replace then?

 'egg, ham, tomato'.replace('ham', 'spam, ham, spam')
'egg, spam, ham, spam, tomato'


If the pattern you want to match is more complicated, have a look at
the re module!

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


Re: Py 3.3, unicode / upper()

2012-12-19 Thread Thomas Bach
On Wed, Dec 19, 2012 at 06:23:00AM -0800, wxjmfa...@gmail.com wrote:
 I was suprised to discover this:
 
  'Straße'.upper()
 'STRASSE'
 
 I really, really do not know what I should think about that.
 (It is a complex subject.) And the real question is why?

Because there is no definition for upper-case 'ß'. 'SS' is used as the
common replacement in this case. I think it's pretty smart! :)

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


Re: [newbie] plotting pairs of data

2012-12-19 Thread Thomas Bach
On Wed, Dec 19, 2012 at 05:47:30AM -0800, hugocoolens wrote:
 The data is available in Python in this format:
 ['0.0364771 0.55569', '0.132688 0.808496', '0.232877 0.832833',
 '0.332702 0.849128', '0.432695 0.862158']
 
 I suppose it is possible to plot x versus y using matplotlib, maybe
 separating the data first in two arrays, but I'm not sure whether this
 is necessary.

I think, yes it is necessary to split the data in separate
lists/arrays. Although I find it annoying, too.

In case that not only the if, but also the how is the matter of your
question something like

xs = [ float(x) for x, _ in map(str.split, l) ]
ys = [ float(y) for _, y in map(str.split, l) ]

should do the trick.

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


Re: I need help with graphs in python (2.7.3.1)

2012-12-18 Thread Thomas Bach
Hi,

Most of the tasks you have to do can be achieved quite easily with the
standard library (except the plotting).

On Tue, Dec 18, 2012 at 03:29:49AM -0800, hevymet...@gmail.com wrote:
 These are some steps I need to do first before creating the graph:
 - Get the name of a CSV file from an ini file,
Have a look at the ConfigParser module[1],

 - Next, read a line from this CSV file,
well, the csv module[2] apparently is a good choice for that,

 - Increase a variable depending on the Log level (information,
 - warning, error, critical),
you maybe want to use collections.counter for that[3]. Anyways, I
think matplotlib can handle the counting for you…

 - Read the next line,
this is just iteration over the csv instance you created with your file

 - Then I need to print these results in a Graph.
I use matplotlib for this purpose, have a look at their gallery[4] to
decide what kind of plot best fits your needs.


I'd recommend to install ipython and start playing around with the
modules I just told you. If you are stuck somewhere read the
documentation properly (it's actually all in there) and come back
again if you cannot come up with a solution.


Hope this helps,
 Thomas Bach.

Footnotes: 
[1]  http://docs.python.org/2/library/configparser.html

[2]  http://docs.python.org/2/library/csv.html

[3]  http://docs.python.org/2/library/collections.html#collections.Counter

[4]  http://matplotlib.org/gallery.html

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


Re: Help with unittest2

2012-12-13 Thread Thomas Bach
Hi,

On Thu, Dec 13, 2012 at 07:03:27AM -0800, Daniel Laird wrote:
 I do am import unittest2 as unittest
 The code does not fail but any use of the new functions results in:
 NameError: global name 'assertListEqual' is not defined
 
 What am I doing wrong?

Read the error message again: it says that it cannot find the _global_
name 'assertListEqual'!

assertListEqual is a method of unittest.TestCase. Hence, it has to be
called on a unittest.TestCase instance, such as

import unittest

class FooTests(unittest.TestCase):

def test_a_list(self):
a = ['foo', 'bar']
b = ['foo', 'bar']
self.assertListEqual(a, b)

BTW, I actually never used 'assertTypeEqual'. I rather call
assertEqual and let unittest do the internals. I think assertEqual
calls the right method for you depending on the arguments type. If you
want to make sure that something is of a certain type use
assertIsInstance!

Hope this helps,

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


Re: CSV out of range

2012-12-04 Thread Thomas Bach
Hi there,

Please be a bit more precise…

On Tue, Dec 04, 2012 at 12:00:05PM +0100, Anatoli Hristov wrote:
 
 The problem comes when I try to index the SKU array and the field is
 empty

Can you provide an example for that?

 and it seems that there I have empty array, I wanted to ignore the
 empty arrays using if statement, but it does the same.

Please provide a small, runable example with the actual code you tried
that raises the exception and the complete trace back.

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


Re: scope, function, mutable

2012-12-04 Thread Thomas Bach
Hi,

On Tue, Dec 04, 2012 at 02:55:44PM +0400, gusa...@gmail.com wrote:
 What is the appropriate definition for the following behavior in Python 2.7
 (see code below).

It has something to do with mutability of lists and that Python passes
around references and not the actual objects.

 
 def f1(x):
 x = [44] + x[1:]
 x[1] = 99
 
 def f2(x):
 x[1] = 99
 x = [44] + x[1:]
 x[3] = 99
 
 t = [1,2,3,4,5,6,7]
 f1(t)
 print t# [1, 2, 3, 4, 5, 6, 7]
 t = [1,2,3,4,5,6,7]
 f2(t)
 print t# [1, 99, 3, 4, 5, 6, 7]

Put that code in e.g. file.py and run

python -m pdb file.py

this will drop you off in the debugger. Step through your code line by
line (using ‘s’) and see how the function calls affect your list
(e.g. via ‘print x’/‘print t’). If this confuses you further… Well,
tell me that my autodidact methodology did not work out at all and ask
again. ;)

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


Re: List problem

2012-12-02 Thread Thomas Bach
On Sun, Dec 02, 2012 at 04:16:01PM +0100, Lutz Horn wrote:
 
 len([x for x in l if x[1] == 'VBD'])
 

Another way is

sum(1 for x in l if x[1] == 'VBD')

which saves the list creation.

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


Re: Compare list entry from csv files

2012-11-29 Thread Thomas Bach
Can you please cut the message you are responding to the relevant
parts?

On Thu, Nov 29, 2012 at 11:22:28AM +0100, Anatoli Hristov wrote:
 The only problem I have is that I cant compare other field than the
 first one in
 for ex_phone in phones:
 telstr = ex_phone[0].lower()
 When I use telstr = ex_phone[0].lower() it says out of range and the
 strange think is that the range is 6 I can't figure that out.

As I understood it phones is an csv.reader instance and you are
iterating repeatedly over it. But, csv.reader does not work this
way. You either have to reinstantiate phones with a fresh
file-descriptor (not so good) or cache the values in an appropriate
data structure (better) e.g. a list.

 import csv
 
 # Open the file with the names and addresses
 origf = open('c:/Working/vpharma.csv', 'rt')
 # Open the  file with the phone numbers
 secfile = open('c:/Working/navori.csv', 'rt')

Note that you never close origf and secfile.

 […]
 # Reads the file with the phone numbers
 # Format First name,Lastname,Address,City,Country,Phone
 phones = csv.reader(secfile, delimiter=';')

So this should probably be
PHONES = list(csv.reader(secfile, delimiter=';'))

(in uppercase letters as it is a global)

 […]
 if __name__ == '__main__':
 name_find()
 
 # Writes the list to a file
 wfile  = open('c:/Working/ttest.csv', wb)
 writer = csv.writer(wfile, delimiter=';')
 for insert in namelist:
 writer.writerow(insert)
 wfile.close()

This should go either in the if __name__ = … part or in a function
on its own.

Also have a look at the with statement you can use it in several
places of your code.

There are several other improvements you can make:
+ instead of having the file-names hard coded try to use argparse to
  get them from the command-line,
+ let functions stand at their own and use less globals,
+ try to avoid the use of the type of the data structure in the name
  (e.g. names is IMHO a better name then namelist),
+ add tests.

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


Re: Re: Managing multiple packages

2012-11-27 Thread Thomas Bach
On Mon, Nov 26, 2012 at 07:58:22PM -0600, Evan Driscoll wrote:
 I'm also pretty confused about the
 distutils/setuptools/distribute/distutils2 landscape and what the
 differences are (at least between the first 3) and what their
 relationships with standard Python are.

In my opinion packaging in Python is at the moment a disaster. The
whole distutils/setuptools/whatever confusion is at least one of the
major sources that this whole topic is so poorly documented and
obviously violates the Zen of Python. Anyways, I think THEY are
working on it. [1] is also a bit clarifying.

Regards,
Thomas.


Footnotes: 
[1]  
http://ziade.org/2010/03/03/the-fate-of-distutils-pycon-summit-packaging-sprint-detailed-report/

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


Re: Web Frameworks Excessive Complexity

2012-11-22 Thread Thomas Bach
On Wed, Nov 21, 2012 at 12:49:52PM -0800, rh wrote:
 
 wheezy + myvirtualenv = 3.3MB
 pyramid = 92MB

$ mkvirtualenv --no-site-packages -p python2.7 pyramid
$ pip install -U distribute
$ pip install pyramid
$ du -h .virtualenvs/pyramid 
22M .virtualenvs/pyramid
$ du -s .virtualenvs/pyramid/lib/python2.7/site-packages/* | sort -n | tail -n 
5 
728 .virtualenvs/pyramid/lib/python2.7/site-packages/pip-1.1-py2.7.egg
1556.virtualenvs/pyramid/lib/python2.7/site-packages/setuptools
1724.virtualenvs/pyramid/lib/python2.7/site-packages/zope
2044.virtualenvs/pyramid/lib/python2.7/site-packages/chameleon
6312.virtualenvs/pyramid/lib/python2.7/site-packages/pyramid

I think 22 MB are OK given the functionality Pyramid has to offer.

Just my 2 cents,
 Thomas.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: method that can be called from a class and also from an instance

2012-11-22 Thread Thomas Bach
On Thu, Nov 22, 2012 at 10:52:56AM -0500, Dave Angel wrote:
 On 11/22/2012 10:14 AM, Marc Aymerich wrote:
  I want to create a method within a class that is able to accept either a 
  class or an instance.
 
 
 I haven't tried it, but how about if you do a @classmethod decorator,
 and then just use isinstance(param, MyClass) ?
 

This won't work:

In [22]: class Foo(object):
   : @classmethod
   : def bar(cls):
   : print repr(cls)
   : 

In [23]: Foo.bar()
class '__main__.Foo'

In [24]: Foo().bar()
class '__main__.Foo'

Actually help(classmethod) explicitly says so:
quote
It can be called either on the class (e.g. C.f()) or on an instance
(e.g. C().f()).  The instance is ignored except for its class.
/quote

I think the way to go is via the descriptor protocol[1] as suggested
by Peter.

Regards,
Thomas.


Footnotes: 
[1] http://docs.python.org/3/howto/descriptor.html

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


Re: Managing multiple packages

2012-11-22 Thread Thomas Bach
On Tue, Nov 20, 2012 at 03:24:59PM -0600, Evan Driscoll wrote:
 
 Suppose I have packages A-C. In addition to being modules in the Python
 sense, they are logically distinct, probably sit in different
 repositories, etc., so there's a directory layout like
 
 [SNIP]

 Finally, suppose that you're changing between editing all three modules.
 
 
 How do you deal with this?

I am using virtual environments and do a

python setup.py develop

on each package. This just creates a symbolic link to the package and
all edits show up immediately.

I have not come up with a good solution for tox, yet.

Hope this helps,

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


Re: editing conf file

2012-11-16 Thread Thomas Bach
On Fri, Nov 16, 2012 at 01:48:49PM +0100, chip9munk wrote:
 configparser has four functions: get, getboolean, getfloat and getint.
 
 how do I get list from cfg file?!

AFAIK you have to parse the list yourself. Something like

my_list = [ s.strip() for s in cp.get('section', 'option').split(',') ]

if you use a comma as a separator.

Have a look at YAML if this is not enough for you, as I think lists
are supported there. Haven't had a look myself though, yet.

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


Re: Help building a dictionary of lists

2012-11-13 Thread Thomas Bach
On Mon, Nov 12, 2012 at 11:41:59PM +, Joshua Landau wrote:
 
 Dict comprehension:
 {i:[] for i in [Test 1, Test 2, Test 3]}

In Python 2.6 this syntax is not supported. You can achieve the same
there via

dict((i, []) for i in ['Test 1', 'Test 2', 'Test 3'])

Also have a look at ``collections.defaultdict``.

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


Re: How to use while within the command in -c option of python?

2012-10-13 Thread Thomas Bach
On Sat, Oct 13, 2012 at 12:32:41AM +, Steven D'Aprano wrote:
 
  He gets SyntaxError because you can't follow a semicolon with a
 statement that begins a block.

Can someone provide a link on where to find this type of information?
I was just hunting through “The Python Language Reference” and could
not find anything explicit. The only thing I found is

http://docs.python.org/reference/simple_stmts.html

“Several simple statements may occur on a single line separated by
semicolons.”

Anyways, this does not explicitly say “You shall not put a compound
statement after a simple statement separated by a semicolon.”, right?

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


Re: Unpaking Tuple

2012-10-08 Thread Thomas Bach
Hi there,

On Sat, Oct 06, 2012 at 03:08:38PM +, Steven D'Aprano wrote:
 
 my_tuple = my_tuple[:4]
 a,b,c,d = my_tuple if len(my_tuple) == 4 else (my_tuple + (None,)*4)[:4]
 

Are you sure this works as you expect? I just stumbled over the following:

$ python
Python 3.2.3 (default, Jun 25 2012, 23:10:56) 
[GCC 4.7.1] on linux2
Type help, copyright, credits or license for more information.
 split = ['foo', 'bar']
 head, tail = split if len(split) == 2 else split[0], None
 head
['foo', 'bar']
 tail
 

I don't get it! Could someone help me, please? Why is head not 'foo'
and tail not 'bar'?

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


[issue16110] Provide logging.config.configParserConfig

2012-10-06 Thread Thomas Bach

Thomas Bach added the comment:

Yeah, the change you suggest sounds reasonable.

Thanks for reconsidering the case!

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue16110
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: unit testing class hierarchies

2012-10-02 Thread Thomas Bach
On Tue, Oct 02, 2012 at 02:27:11PM +0200, Ulrich Eckhardt wrote:
 As you see, the code for test_base() is redundant, so the idea is to
 move it to a baseclass:
 
 class TestBase(unittest.TestCase):
 def test_base(self):
 ...
 
 class TestD1(TestBase):
 def test_r(self):
 ...
 def test_s(self):
 ...
 
 class TestD2(TestBase):
 def test_x(self):
 ...
 def test_y(self):
 ...

Could you provide more background? How do you avoid that test_base()
runs in TestD1 or TestD2?

To me it sounds like test_base() is actually no test. Hence, I would
rather give it a catchy name like _build_base_cls().  If a method name
does not start with 'test' it is not considered a test to run
automatically.

Does this help?

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


Slicing iterables in sub-generators without loosing elements

2012-09-29 Thread Thomas Bach
Hi,

say we have the following:

 data = [('foo', 1), ('foo', 2), ('bar', 3), ('bar', 2)]

is there a way to code a function iter_in_blocks such that

 result = [ list(block) for block in iter_in_blocks(data) ]

evaluates to

 result = [ [('foo', 1), ('foo', 2)], [('bar', 3), ('bar', 2)] ]

by _only_ _iterating_ over the list (caching all the elements sharing
the same first element doesn't count)?

I came up with the following

def iter_in_blocks(iterable):
my_iter = iter(iterable)
while True:
first = next(my_iter)
pred = lambda entry: entry[0] == first[0]
def block_iter():
yield first
for entry in itertools.takewhile(pred, my_iter):
yield entry
yield block_iter()

which does not work as itertools.takewhile consumes the first entry
not fulfilling the pred.

I currently have the intuition that the problem is not solvable
without using e.g. a global to pass something back to iter_in_blocks
from block_iter. Any other suggestions?

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


Re: Slicing iterables in sub-generators without loosing elements

2012-09-29 Thread Thomas Bach
On Sat, Sep 29, 2012 at 09:26:00AM -0700, Paul Rubin wrote:
 Thomas Bach thb...@students.uni-mainz.de writes:
 
 itertools.groupby(data, lambda (x,y) : x)
 
 is basically what you want.

True!

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


Re: Dynamically determine base classes on instantiation

2012-08-16 Thread Thomas Bach
On Thu, Aug 16, 2012 at 12:16:03AM +, Steven D'Aprano wrote:
 Some comments:
 
 1) What you show are not use cases, but examples. A use-case is a 
 description of an actual real-world problem that needs to be solved. A 
 couple of asserts is not a use-case.

Thanks for the clarification on that one. So, here's the use-case: I'm
querying the crunchbase API which returns JSON data and is rather
poorly documented. I want to create a data model for the companies
listed on Crunchbase in order to be able to put the queried data in a
data-base. As I am too lazy to examine all the data by hand I thought
I automatize this. I thought that it would be nice to be able to pass
a function a parsed JSON object (AFAIK these are lists, dicts,
strings, ints, floats, strs in Python) and it returns me the type of
these objects. For the simple classes (str, int, float) this is quite
trivial: F('foo') should return `str' and F(8) should return `int'.

For a compound object like dict I would like it to return the data
fields with their type. Hence, F({'foo': 8}) should return 
{'foo': int}, and given that f = F({'foo': {'bar': 80}}) I would like
f to equal to {'foo': dict}, with the option to query the type of
'foo' via f.foo, where the latter should equal to {'bar': int}. So
far, this is not a complicated case. But, sometimes a data field on
returned data set is simply None. Thus, I want to extract the types from
another data set and merge the two.

So, my question (as far as I can see it, please correct me if I am
wrong) is less of the How do I achieve this?-kind, but more of the
What is a clean design for this?-kind. My intuitive thought was that
the `merge' function should be a part of the object returned from `F'.

 How about you tell us the problem, and we'll suggest a solution?

I can see your point. On the other hand, by expressing my thoughts you
can at least tell me that these are completely wrong and correct my
way of thinking this way.

 Consider your two examples:
 
 a = Foo(['a', 'list'])
 b = Foo({'blah': 8})
 
 According to your design:
 
 a is a Foo
 b is a Foo

I actually never said that. I simply wanted `a' and `b' to share the
same function (the `merge' function), I thought that the easiest way
to achieve this is by letting them share the same name-space. But, as
you show: …

 therefore a and b are the same type
 
 So far so good: this is perfectly normal object-oriented design.
 
 But you also have 
 
 a is a list, but not a dict
 b is a dict, but not a listn
 therefore a and b are different types
 
 So you contradict yourself: at the same time, a and b are both the same 
 and different types.

… I already made a mistake on the logical level.

 Instead, Foo should implement only the shared operations, and everything 
 else should be delegated to _obj.
 
 If you inherit from builtins, you cannot use automatic delegation on the 
 magic double-underscore (dunder) methods like __eq__, __len__, etc.
 
 See this thread here for one possible solution:
 
 http://www.velocityreviews.com/forums/t732798-automatic-delegation-in-python-3-a.html
 

OK, thanks for the hint. I will see how I'm going to put all this
stuff together.

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


Re: Dynamically determine base classes on instantiation

2012-08-16 Thread Thomas Bach
On Thu, Aug 16, 2012 at 05:10:43PM +0200, Hans Mulder wrote:
 On 16/08/12 14:52:30, Thomas Bach wrote:
  
  So, my question (as far as I can see it, please correct me if I am
  wrong) is less of the How do I achieve this?-kind, but more of the
  What is a clean design for this?-kind. My intuitive thought was that
  the `merge' function should be a part of the object returned from `F'.
 
 The misunderstanding is that you feel F should return an object with
 a 'merge' method and a varying abse type, while Steven and others
 think that F should be a function.

OK, then my design wasn't so bad in the first place. :)

I made a class `Model' which wraps the actual type and realized
`merge' and `F' (with a better name, though) as classmethods of
`Model' in order to tie together the stuff that belongs together. By
the way, another need I saw for this design was that

setattr(Model(), 'foo', {'bar': int})

works, whereas 

setattr(dict(), 'foo', {'bar': int}) 

raises an AttributeError (on Python 3.2). Could someone give me the
buzz word (or even an explanation) on why that is so?

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


Re: Dynamically determine base classes on instantiation

2012-08-16 Thread Thomas Bach
On Thu, Aug 16, 2012 at 12:29:21PM -0400, Dennis Lee Bieber wrote:
 On Thu, 16 Aug 2012 14:52:30 +0200, Thomas Bach
 thb...@students.uni-mainz.de declaimed the following in
 gmane.comp.python.general:
 
   Of course, since the parse result (at least from my recent
 experiment) is a Python structure, it isn't difficult to walk that
 structure...

I prefer that one, as I have the parsed data already lying around in
memory. But, as I think about it, I could also pass it to json.dumps
and parse it again. But, that wouldn't make much sense, right?

 
   But, sometimes a data field on returned data set is simply None.
 Thus, I want to extract the types from another data set and merge the
 two. ??? A data field /value/ of None has the /type/ type
 'NoneType', so I don't quite understand what you intend to merge? You
 can't arbitrarily change the type without changing the value.

OK, I am probably using the wrong vocabulary here again. :(

Imagine you have two data sets:

d1 = {'foo': None}
d2 = {'foo': 8}

Where I would assume that d1 has foo not set. That's why I want this
whole merge-thing in the first place: to be able to extract the type
{'foo': None} from d1 and {'foo': int} from d2 and merge the two
together which should result in {'foo': int}.

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


Re: Dynamically determine base classes on instantiation

2012-08-16 Thread Thomas Bach
On Thu, Aug 16, 2012 at 10:03:51AM -0700, Richard Thomas wrote:
 class Foo(object):
 def __new__(cls, arg):
 if isinstance(arg, list):
 cls = FooList
 elif isinstance(arg, dict):
 cls = FooDict
 return object.__new__(cls, arg)
 
 class FooList(Foo, list):
 pass
 
 class FooDict(Foo, dict):
 pass
 
 You could even have __new__ make these Foo* classes dynamically when
 it encounters a new type of argument.
 
 Chard.

Thanks for that one. Your solution just hit me like a punch in the
face. I had something similar in my mind. But I could not work out how
the mechanics behind it are working.

Regards,

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


Dynamically determine base classes on instantiation

2012-08-15 Thread Thomas Bach
Hi list,

I'm confronted with a strang problem I cannot find a clean solution
for. To me it seems like I need meta-classes. Anyway, I stucked a bit
deeper in that topic and couldn't find a proper solution neither. But,
judge for yourselve.

I want a class that determines on instantiating its base classes
dynamically. Consider the following two use cases

a = Foo(['a', 'list'])  # returns an instance that behaves like a list
assert len(a) == 2
assert a[0] == 'a'
assert a == ['a', 'list']
assert isinstance(a, list) # This would be nice, but no must-have

b = Foo({'blah': 8}) # returns an instance that behaves like a dict
assert b['blah'] == 'blah'
assert b == {'blah': 8}
assert isinstance(b, dict) # again, no must-have

a.do_something()   # common function to both instances as defined
b.do_something()   # in the Foo class


What I'm currently doing something like the following:

class Foo(object):

def __init__(self, obj):
self._obj = obj

def __len__(self):
return len(self._obj)

def __getitem__(self, name):
return self._obj[name]

# …

def do_something(self):
# do something on self._obj
pass

Which seems ugly. Is there a way to provide the functions of `list'
and `dict' in Foo's look-up path without having to write all the
stubs myself?

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


Re: Compiling Python (modules) on 64bit Windows - which compiler suite?

2012-03-21 Thread Thomas Bach
Hi,

Ralph Heinkel ralph.hein...@web.de writes:

 Hi,

 when processing our mass spectrometry data we are running against the
 2GB memory limit on our 32 bit machines. So we are planning to move to
 64bit. Downloading and installing the 64bit version of Python for
 Windows is trivial, but how do we compile our own C extension? 

What about installing Cygwin and using the shipped GCC?

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


Re: standalone python web server

2012-02-09 Thread Thomas Bach
Rita rmorgan...@gmail.com writes:

 I am building a small intranet website and I would like to use
 Python. I was wondering if there was a easy and medium performance
 python based web server available. 

Are you going to use a framework? Most of these ship with a light
web server implementation… You probably want to check these out too…

I got a pretty robust setup via
+ nginx,
+ supervisord,
+ the web server shipped with Pyramid

If you want to use the WSGI standard I'd recommend to read

http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/deployment.html
 

This document describes several possible set ups to serve an WSGI
application…


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


Re: Getting the current directory path and the path where python script is saved

2011-12-13 Thread Thomas Bach
gialloporpora gialloporp...@gmail.com writes:

 I would like to know how to obtain the path where script is executed
 and the path where the file script is stored.

Does this help:

In [16]: import os

In [19]: os.getcwd()
Out[19]: '/home/vince'

In [21]: os.__file__
Out[21]: '/home/vince/src/pyramid_install/lib/python2.7/os.pyc'

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


Re: unittest. customizing tstloaders / discover()

2011-12-12 Thread Thomas Bach
Gelonida N gelon...@gmail.com writes:

 Do I loose anything if using nose. or example can all unit tests / doc
 tests still be run from nose?

AFAIK you don't loose anything by using nose – the unittests should all
be found and doctests can be run via `--with-doctest', I never used
doctests though.

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


Re: unittest. customizing tstloaders / discover()

2011-12-11 Thread Thomas Bach
Gelonida N gelon...@gmail.com writes:

 I'd like to use regular expresions as include / exclude rules
 and I would like to have another filter function, which would check for
 the existence of certain metavariabels in test suite files

Did you have a look at nose? I'm using it and it supports
include/exclude rules via RE and lets you select directories to run
tests from.

I'm not sure about the meta-variable thing, but it supports plug ins
that could do the trick…

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