Re: the annoying, verbose self

2007-11-21 Thread Farshid Lashkari
braver wrote:
 Is there any trick to get rid of having to type the annoying,
 character-eating self. prefix everywhere in a class?  Sometimes I
 avoid OO just not to deal with its verbosity.  In fact, I try to use
 Ruby anywhere speed is not crucial especially for @ prefix is better-
 looking than self.
 
 But things grow -- is there any metaprogramming tricks or whatnot we
 can throw on the self?

The most common answer you are going to get is that explicit is better 
than implicit, which I tend to agree with. Some people use 's' instead 
of 'self'. This shortens the number of characters you have to type, and 
is only one character more than the Ruby '@' prefix.

Here is a metaprogramming technique that removes self, but I don't 
recommend these sorts of things, especially if other people are going to 
be looking at your code in the future. So use it at your own risk!

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362305

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


Re: Python strings question (vertical stack)

2007-11-20 Thread Farshid Lashkari
dmitrey wrote:
 Hi all,
 I have some strings, let it be string1, string2, string3.
 
 So how could String=
 
 string1
 string2
 string3
 
 
 be obtained?
 
 Thank you in advance, D.

If you just want the to add newlines between the strings then you can do 
the following:

String = '\\n'.join([string1,string2,string3])

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


Re: Python strings question (vertical stack)

2007-11-20 Thread Farshid Lashkari
J. Clifford Dyer wrote:
 I think you mean '\n'.join([string1,string2,string3])
 
 You actually do want the \ to do its thing in this case.

Yeah, my brain must still be asleep. Thanks for waking it up :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simple? embedding question

2007-10-31 Thread Farshid Lashkari
[EMAIL PROTECTED] wrote:
 it works!
 could i cache maindict pointer in a global var or am i condemned to
 call
 PyObject* mainmod = PyImport_AddModule(__main__);
 assert(mainmod);
 PyObject* maindict = PyModule_GetDict(mainmod);
 assert(maindict);
 every time i want to PyRun_String?
 i call Py_Finalize only atexit.
 
 i also found boost library docs of some help:
 http://service-spi.web.cern.ch/service-spi/external/Boost/1.30.0/rh73_gcc32/libs/python/doc/tutorial/doc/using_the_interpreter.html
 
 btw what kind of object is returned in case i use Py_file_input
 in PyRun_String?
 

Yes, you can keep a reference to maindict if you wish, but make sure you 
increment the reference count since PyModule_GetDict() returns a 
borrowed reference.

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


Re: simple? embedding question

2007-10-30 Thread Farshid Lashkari
[EMAIL PROTECTED] wrote:
 suppose i have imported two modules foo and bar with
 foo=PyImport_ImportModule(foo) and bar=PyImport_ImportModule(bar)
 respectively.
 
 Now suppose I have an artitrary python expression to evaluate.
 Do I need to parse that thring and check for foo. and bar. before
 jumping the usual
 PyModule_GetDict,PyDict_GetItemString,PyObject_CallObject hoop hoop on
 the PyObject for
 the prefix or there is a better way?
 
 btw PyRun_SimpleString(foo.baz()); does not work:
  Traceback (most recent call last):
   File string, line 1, in ?
 NameError: name 'foo' is not defined
 
 and i potentially need a PyObject* back with the result of the
 expression anyway.
 

I believe the problem is that you are not importing the foo and bar 
modules into the __main__ scope. Try using PyImport_ImportModuleEx, 
which will allow you to specify the global scope to import the module 
into. For example, to import the modules into the __main__ scope you 
could do the following:

PyObject* mainmod = PyImport_AddModule(__main__);
PyObject* maindict = PyModule_GetDict(mainmod);

foo = PyImport_ImportModuleEx(foo, maindict , maindict , NULL);
bar = PyImport_ImportModuleEx(bar, maindict , maindict , NULL);

Once the modules are imported into the __main__ scope, you should be 
able to use PyRun_SimpleString() to evaluate expressions.

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


Re: simple? embedding question

2007-10-30 Thread Farshid Lashkari
[EMAIL PROTECTED] wrote:
 i switched to PyImport_ImportModuleEx per your suggestion but i still
 get
 
 Traceback (most recent call last):
   File string, line 1, in ?
 NameError: name '__main__' is not defined
 
 i tried PyRun_SimpleString(__main__.foo.baz()); :
 Traceback (most recent call last):
   File string, line 1, in ?
 NameError: name '__main__' is not defined
 
 i do not have if __name__ == '__main__':
 statement anywhere in the module i'm importing,
 but nevertheless i checked that PyImport_AddModule(__main__);
 and subsequent getdict return non null pointers.
 does non null dictionary indicate that PyImport_AddModule
 succeeded as opposed to creating an empty module object?

Sorry, I misunderstood the behavior of the PyImport_ImportModuleEx() 
function. You can use the PyImport_AddModule() function as before, but 
you must explicitly add the module to the __main__ module. Here is some 
code:

PyObject *mainmod = PyImport_AddModule(__main__);
PyObject *foo = PyImport_ImportModule(foo);
Py_INCREF(foo); //Increment foo module since PyModule_AddObject() steals 
reference
PyModule_AddObject(mainmod, foo, foo);
PyRun_SimpleString(foo.baz());

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


Re: C API (embedded Python): How to get and set named variables

2007-09-10 Thread Farshid Lashkari
[EMAIL PROTECTED] wrote:
From the C API (I'm using Python embedded), how can I get and set the
 value of named variables?  Right now, I'm using hacks like
 PyRun_SimpleString(foobar = 12\n), but I'd really like to access the
 named objects directly.
 

You can use the following C functions to set/get named attributes of an 
object:

PyObject_SetAttrString
PyObject_GetAttrString

If the attributes belong to the global scope of a module, then you can 
use PyImport_AddModule to get a handle to the module object. For 
example, if you wanted to get the value of an integer in the __main__ 
module named foobar, you would do the following:

PyObject *m = PyImport_AddModule(__main__);
PyObject *v = PyObject_GetAttrString(m,foobar);

int foobar = PyInt_AsLong(v);

Py_DECREF(v);

You will probably want to add some error checking in your code.

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


Re: Subclassing zipfile (new style class)

2007-09-06 Thread Farshid Lashkari
Larry Bates wrote:
 import zipfile
 class walkZip(zipfile):
 pass
 
 
 if __name__ == __main__:
 print Hello World
 
 Traceback (most recent call last):
   File string, line 192, in run_nodebug
   File module1, line 2, in module
 TypeError: Error when calling the metaclass bases
 module.__init__() takes at most 2 arguments (3 given)

In your code 'zipfile' is a module, not a class, so you cannot inherit 
from it. I believe this is what you are trying to accomplish:

class walkZip(zipfile.ZipFile):
 pass

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


Re: Question about embedding python in C++

2007-08-23 Thread Farshid Lashkari
TheShadow wrote:
 When extending python in c/c++ after you register a module is there a
 way in c/c++ to check if they were correctly registered?
 
 Cause I'm having the problem where when I execute the the python
 script it finds the module but none of the functions.
 

Are you calling Py_InitModule(...) in your initmodule function? If so, 
Py_InitModule(...) returns a reference to the module object. You can use 
this object to double check that your function names exist in the 
modules dictionary. Most likely, there is an error in your code. If you 
post it, it would be easier to tell what the problem is.

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


Re: Catching SystemExit in C API code when embedding Python?

2007-08-02 Thread Farshid Lashkari
Stefan Bellon wrote:
 Hi all!
 
 I am embedding Python into a GUI application in a way that the GUI is
 scriptable using Python.
 
 Now I have come to a problem that when the user puts a sys.exit(0)
 into his script to end the script, not only the script is terminated,
 but also the GUI application itself. This is not the intended behaviour.
 
 As in Python itself you can catch SystemExit, I think this should be
 the way to go. But how do I catch this exception from within the C API?
 
 Thanks in advance for any hints.
 

Have a look at the following doc page for handling exceptions with the C 
api:

http://docs.python.org/api/exceptionHandling.html

Also, here is some sample code that will catch system exit exceptions:

//Call python code
...
//Check for system exit exception
if(PyErr_Occurred()) {
 if(PyErr_ExceptionMatches(PyExc_SystemExit)) {
 //handle system exit
 PyErr_Clear();
 } else {
 PyErr_Print();
 }
}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Catching SystemExit in C API code when embedding Python?

2007-08-02 Thread Farshid Lashkari
Stefan Bellon wrote:
 Thanks for your hints ...
 
 The interesting part is Call python code. In my example this is done
 with PyRun_SimpleString which does not return if an exception is not
 handled but raised out of the interpreter. So I am unsure of what you
 mean with Call python code.
 
 When installing an excepthook (see my other posting), then I can indeed
 catch all exceptions ... except for SystemExit which is the one I'm
 after.
 

You cannot use PyRun_SimpleString, since it will automatically print and 
clear the error. You will need to use PyRun_String instead.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another C API Question

2007-07-27 Thread Farshid Lashkari
beginner wrote:
 This works with PyFloat only. It does not work with integers.

Did you try it out? I have used it on ints, bools, and objects that 
implement the __float__ method. It does not work on strings though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another C API Question

2007-07-27 Thread Farshid Lashkari
beginner wrote:
 I did and it did not seem to work. I ended up doing the following.
 Verbose, isn't it?
 If I do d=PyFloat_AsDouble(oDiscount); in the third if, I get an
 error. Maybe I missed something obvious.

That's strange. I just tried the following code:

fprintf(stdout,True = %lf\n,PyFloat_AsDouble(Py_True));
fprintf(stdout,False = %lf\n,PyFloat_AsDouble(Py_False));
fprintf(stdout,5 = %lf\n,PyFloat_AsDouble(PyInt_FromLong(5)));

And it printed the following:

True = 1.00
False = 0.00
5 = 5.00

What version of Python are you using?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another C API Question

2007-07-26 Thread Farshid Lashkari
beginner wrote:
 I know obj is a number, but I do not know the exact type. How can I
 convert it to double without writing a giant switch() that exhausts
 every single type of number?

Try using the PyFloat_AsDouble(...) function, it should be able to 
convert an object to a double, as long as the object implements the 
__float__ method.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pydoc with METH_VARGS

2007-06-25 Thread Farshid Lashkari
Stuart wrote:
 I'm asking if there's some sort of commenting or input file or
 something to customize the output pydoc generates. Thanks.

AFAIK, there is no way to do this. However, you can edit the doc string 
for your function, which can include the argument list. I believe this 
is what most of Python's built-in functions do.

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


Re: EMBEDDING Run Python Run C Function

2007-06-22 Thread Farshid Lashkari
[EMAIL PROTECTED] wrote:
 At the moment i can run python-string-code from C (MinGW, WinXP)
 
 But how can i register a C-function in python-RUNTIME and call this C
 function from python - without wrapper dll's or libs???

Have a look at the following documentation page on extending/embedding 
python. I believe it does exactly what you want.

http://www.python.org/doc/ext/extending-with-embedding.html

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


Re: how to convert an integer to a float?

2007-02-27 Thread Farshid Lashkari
[EMAIL PROTECTED] wrote:
 Hi, I have the following functions,  but ' dx = abs(i2 - i1)/min(i2,
 i1)' always return 0, can you please tell me how can i convert it from
 an integer to float?

When two integers are involved in a division, the result will also be a 
division. If one of the operands is a float, then the result will be a 
float instead. So try casting one of the values to a float before 
performing the division:

dx = float(abs(i2 - i1))/min(i2, i1)

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


Re: how to convert an integer to a float?

2007-02-27 Thread Farshid Lashkari
Farshid Lashkari wrote:
 When two integers are involved in a division, the result will also be a 
 division.

My bad, I meant the result will also be an *integer*

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


Re: f---ing typechecking

2007-02-14 Thread Farshid Lashkari
Szabolcs Nagy wrote:
 L=[1]
 L.extend((1,))
 L
 [1, 1]

Are list.extend() and list concatenation supposed to behave differently? 
I always thought concatenation was just shorthand for calling extend().

However the following seems to work:

  L = [1]
  L += (2,)
  L
 [1, 2]

It seems like the '+' operator for lists should accept any iterable for 
the right side argument to be consistent with extend() and the '+=' 
operator.

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


Re: sending string or list to a function

2006-12-04 Thread Farshid Lashkari
manstey wrote:
 Is there a neat way to write a function that can receive either a
 string or a list of strings, and then if it receives a string it
 manipulates that, otherwise it manipulates each string in the list?

The following code shows one way you can accomplish this. I don't 
consider it bad programming style to allow your functions to accept 
multiple data types.

def MyFunction(val):
 if isinstance(val,basestring):
 val = [val]
 for s in val:
 #Process string


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


Re: Multithreaded C API Python questions

2006-11-09 Thread Farshid Lashkari
Svein Seldal wrote:
 I'm unable to get access to python as long as another python call is 
 executing. The PyEval_AcquireThread() call blocks until the first call 
 returns. I was hoping that the python system itself would release the 
 GIL after some execution, but it itsnt.
 
 I am dependent upon the ability to have to threads executing in python 
 land at the same time. How can this be done?

Are you creating your threads through python or through C code? If you 
are only creating it through C code, then make sure you initialize the 
GIL with the following call at the beginning of your application:

PyEval_InitThreads()

 From my experience, calling PyGILState_Ensure() was enough. I didn't 
need to call any extra threading functions. But make sure that every 
call to PyGILState_Ensure() is matched with a call to PyGILState_Release()

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


Re: is this the right way to do subclasses?

2006-11-08 Thread Farshid Lashkari
John Salerno wrote:
 Ok, back to my so-called game. I'm just curious if I've implemented 
 the subclasses properly, because it seems like an awful lot of 
 repetition with the parameters. And again, if I want to add a new 
 attribute later, I'd have to change a lot of things. I can't help but 
 get the feeling that I'm doing something very inefficiently.

Just accept variable arguments in the constructor of the sub-classes and 
forward them to the base class.

class Fighter(Character):

 def __init__(self, *args, **kw):
 Character.__init__(self, *args, **kw)
 self.health += 2
 self.strength += 1

This way, if you add a new parameter to the base class, you won't need 
to update all the derived classes.

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


Re: C wrapper

2006-11-07 Thread Farshid Lashkari
Sheldon wrote:
 Can anyone give me some idea as to what this error means?
 
 ImportError: dynamic module does not define init function 
 
 I am new at this and there is still a lot to learn.
 
 Any help is appreciated,

Take a look at the documentation for creating extension modules, 
especially the following page:

http://docs.python.org/ext/methodTable.html

The initialization function must be named initname(), where name is the 
name of the module, and should be the only non-static item defined in 
the module file

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


Hooking file open

2006-11-01 Thread Farshid Lashkari
Hi,

My goal is to detect all (or most) file dependencies of a script (i.e. 
modules, dlls, data files). Currently, after a script is finished 
executing I use sys.modules to determine all module dependencies, and I 
use win32process.EnumProcessModules to determine DLL dependencies. This 
works reasonably well, however I would still like to detect dependencies 
from regular file open calls.

I did a little test by modifying __builtins__.open to point to a custom 
function that forwards the call to the original open function and saves 
the filename to a list. It seemed to work for simple test cases. Here is 
the code:

def open_hook(*args,**kwargs):
 r = open_real(*args,**kwargs)
 saveFileName(args[0])
 return r

open_real = __builtins__.open
__builtins__.open = open_hook

Is this a safe approach? Is there a more efficient way of doing this? I 
realize that some dependencies will still fall through my checks, 
especially file opens from C extensions, which is fine. I just want to 
be able to detect the most common use cases. Any other suggestions are 
appreciated.

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


Re: Hooking file open

2006-11-01 Thread Farshid Lashkari
Dale Strickland-Clark wrote:
 You might consider trapping calls to file() too, which is an alias for
 open().

Thanks, I didn't know about that.

 Also, I think I'd do my logging before calling the real function. It depends
 how you want to deal with exceptions. 

I placed the logging after the call to the real function so that files 
that don't exist will not be logged. However, I'm already checking for 
file existence during the post process of the script running, so I guess 
it doesn't really make too much of a difference.

Thanks for the help.

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


Re: What is the cleanest way to for a module to access objects from the script that imports it?

2006-10-27 Thread Farshid Lashkari
[EMAIL PROTECTED] wrote:
 Wouldn't importing and re-importing the same modules cause considerable
 resource bulk? Or does python cache that stuff?

If a module is already imported, then the import statement just uses the 
cached module. However, you can force a full reload of the module using 
the following syntax:

reload(mymodule)

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


Re: cleaner way to write this?

2006-10-25 Thread Farshid Lashkari
John Salerno wrote:
 Hi guys. I'm looking for a nicer, more compact way of writing this code. 
 It doesn't have to be anything fancy, just something without the 
 duplication and preferably only one return statement.
 
 def create_db_name(self):
 dlg = wx.TextEntryDialog(self.frame, 'Enter a database name:',
  'Create New Database')
 if dlg.ShowModal() == wx.ID_OK:
 db_name = dlg.GetValue()
 dlg.Destroy()
 return db_name
 else:
 dlg.Destroy()
 return
 
 One problem is that if Cancel is pressed, I can't return anything. 
 Another problem is that the dialog must be destroyed, so that has to 
 come before any return statements.
 
 Thanks.

This should work:

def create_db_name(self):
 dlg = wx.TextEntryDialog(self.frame, 'Enter a database name:',
  'Create New Database')
 db_name = None
 if dlg.ShowModal() == wx.ID_OK:
 db_name = dlg.GetValue()
 dlg.Destroy()
 return db_name


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


Re: cleaner way to write this?

2006-10-25 Thread Farshid Lashkari
Paul Rubin wrote:
 I like
 
 if dlg.ShowModal() == wx.ID_OK:
  db_name = dlg.GetValue()
 else:
  db_name = None
 dlg.Destroy()
 return db_name
 
 better than
 
 db_name = None
 if dlg.ShowModal() == wx.ID_OK:
  db_name = dlg.GetValue()
 dlg.Destroy()
 return db_name
 
 but I suppose it's a matter of preference.

Yeah, I think the second way is usually used by people who are more 
accustomed to programming in C, since they need to initialize variables. 
Your way is probably more Pythonic though.

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


Re: return tuple from C to python (extending python)

2006-10-24 Thread Farshid Lashkari
Simon Forman wrote:
 I have not done a great deal of extension work with python, however, I
 do not believe you can simply cast an int (or pointer to int, which is
 what you say dat is declared as, unless my C is /really/ rusty) to
 PyObject*.
 
 I think you need to do something like Py_BuildValue(i, 123), but see
 http://docs.python.org/ext/buildValue.html for more info.

Simon is correct. You need to create a python object from your unsigned 
int. Try the following instead:

PyTuple_SET_ITEM(toRet, i, PyInt_FromLong(dat[i]) );

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


Re: storing variable names in a list before they are used?

2006-09-29 Thread Farshid Lashkari
Hi John

John Salerno wrote:
 how would I go about putting these variable names in a list? I know I 
 can't leave them as above, but if I put them in as a string, then how do 
 I later transform them into an actual variable for assign, such as:
 
 first_name = widget.get_text()
 
 Is there some kind of idiom that does this sort of work?

What scope do you want these variable names to show up in? For example, 
if you want them to be defined in the global scope then you can do the 
following:

name = 'first_name'

globals()[name] = widget.get_text()

print first_name


If you want these variables to be assigned to an object then you can use 
setattr():


name = 'first_name'

setattr(obj,name,widget.get_text())

print obj.first_name


Hope this helps

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


Releasing GIL in unknown state

2006-08-29 Thread Farshid Lashkari
Hi,

Is there a proper way for C code to ensure that the GIL is released? I 
know about PyGILState_Ensure and PyGILState_Release, but that is to 
ensure the GIL is acquired. I have some extension code that does heavy 
processing and I want to release the GIL, but the code can't be sure 
that the GIL is already acquired. All I can think of so far is the 
following:

PyGILState_STATE state = PyGILState_Ensure();

Py_BEGIN_ALLOW_THREADS

//do processing

Py_END_ALLOW_THREADS

PyGILState_Release(state)


Is there a better way?

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


Re: Inheritting Built In Types

2006-08-16 Thread Farshid Lashkari
Digital Logic wrote:
 Am I checking for the slice object incorrectly?  That's the only thing
 I can think of.

Yes. The slice object is the i variable in your code, not the data 
variable.

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


Re: error handling

2006-08-10 Thread Farshid Lashkari
Chris wrote:
 But sometimes you can have too many of these statements in your
 program, and it starts to get tangled and nasty looking. Is there a way
 I can modify sys.error so that when the interpreter comes accross an
 IndexError it prints That number is way too big! before it exits?

Hi,

Try placing the try/except block around the main function of your program:

if __name__ == '__main__':
 try:
 main()
 except IndexError:
 sys.exit(That number is way too big!)

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


Re: error handling

2006-08-10 Thread Farshid Lashkari
Steven D'Aprano wrote:
 That's broken. 
 
 Imagine that somewhere in main() the following is called:
 
 D = {a: apple, b: bicycle, c: cat}
 print D[aardvark]
 
 Your code now prints That number is way too big!. That's not good.
 
 try...except blocks should, as a general rule, cover only the smallest
 amount of code that they need to.

Hi Steven,

Point taken and I think your solution better addresses the root of the 
problem. However, the OP said he wanted to print out that error message 
whenever the interpreter came across any IndexError. So I gave him what 
he wanted. I guess he needs to be more careful what he wishes for ;)

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


Re: loop until keypress (Windows XP)

2006-08-09 Thread Farshid Lashkari
placid wrote:
 is there a way to do this, wait for user input but dont block?

Hi,

The msvcrt module should do what you want. Here is a sample:

import msvcrt

chr = 0
while chr != 'q':
  keep printing text 
 if msvcrt.kbhit():
 chr = msvcrt.getch()


Keep in mind that this will only work on windows.

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


Re: Missing MSVCR71.dll

2006-08-08 Thread Farshid Lashkari
The windows distribution of python was compiled with Visual Studio 7.1, 
so you need the 7.1 runtime libraries on your computer to run python. I 
haven't tried compiling an app with VS2005, but I don't see why they 
would be incompatible. I've compiled a python app using VS 7.0 and it 
worked fine.

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


Re: Newbie question: what's with self?

2006-08-08 Thread Farshid Lashkari
donkeyboy wrote:
 This is probably a really basic question, but anyway ...
 
 I'm new to both Python and OO programming. From looking at a number of
 code examples, the word self is used a lot when referring to classes.
 As such, what does self mean and/or do? I've read things that say
 it's a naming convention, but no-one has really spelt it out (in idiot
 form!) in a way I can understand.
 
 Any help you can provide would be great: at the moment, when code
 doesn't work as expected, I'm randomly sprinkling selfs in all over
 the place to see if that helps, but without much of an idea of what it
 really achieves. 
 
 Thanks in advance!!
 

Hi,

Take a look at the following FAQ on the python homepage:

http://www.python.org/infogami-faq/general/why-must-self-be-used-explicitly-in-method-definitions-and-calls/

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


Re: singleton decorator

2006-08-07 Thread Farshid Lashkari
Andre Meyer wrote:
 Am I missing something here? What is the preferred pythonic way of 
 implementing singleton elegantly?

The Open Issues section of that PEP says the following:

It's exceedingly unlikely that class decorators will be in Python 2.4

So it might not be in the current version of python.

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


Re: Calling python functions from C

2006-05-09 Thread Farshid Lashkari
[EMAIL PROTECTED] wrote:
 I want to call add from C. Could anybody please help me?

Look at the Pure Embedding section of the python documentation. It 
contains an example program that does exactly what you want. Here is a 
link to the page:

http://www.python.org/doc/ext/pure-embedding.html

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


Re: can someone explain why ..

2006-04-25 Thread Farshid Lashkari
Schüle Daniel wrote:
 I don't understand what is the difference between commented lines
 1 and 2
 
 with 1 uncommented and 2 commented it works as expected
 with 1 commented and 2 uncommented the picture doesn't appear


I'm not familiar with Tkinter, but it seems as thought with 2, the 
image variable is garbage collected after the constructor of Main is 
called. With 1, you save a reference to the image, so it does not get 
garbage collected.

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


Re: can someone explain why ..

2006-04-25 Thread Farshid Lashkari
Schüle Daniel wrote:
 thx for quick reply :)
 
 image is local variable of imageLabel
 I would expect that in case imageLabel lives, it should
 hold alife objects bound to its local variables
 
 I am just curious *why* reference to image is not hold by imageLabel
 which on his part is hold by frame1 .. which is hold by global root

These are the only lines of code that reference imageLabel:

imageLabel = Label(master = frame1, image = image)
imageLabel.pack()


Unless the constructor of Label adds a reference of itself to frame1, 
imageLabel will also become garbage collected at the end of the 
constructor. Are you sure this is the case?

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


Re: python to c API, passing a tuple array

2006-04-14 Thread Farshid Lashkari
[EMAIL PROTECTED] wrote:
 Hi,
 I want to pass something like this to a C function via the Python C
 API.
 mytuple = ((string_one, 1.2, 1.3), (string_two, 1.4, 1.5), ..,
 .,  )
 This tuple is dynamic in size, it needs to be 3 X N dimensions. each
 tuple in the
 tuple array is of the form (string, float, float) as described above
 
 so from python:
 
 mytuple = ((string_one, 1.2, 1.3), (string_two, 1.4, 1.5))
 api.myCFunction(mytuple)
 
 The C api:
 static PyObject *myCFunction(PyObject *self, PyObject *args)
 {
 
 if (!PyArg_ParseTuple(args, O, . ?)  {
 printf( error in PyArg_ParseTuple!\n);
 return Py_None;
 }
 
 Thanks.
 


Just loop through each item in the arguments and parse the sub-tuple. 
Here is some sample code that doesn't do any error checking:

static PyObject *myCFunction(PyObject *self, PyObject *args)
{
 int numItems, i;
 PyObject *tuple;

 numItems = PyTuple_Size(args);

 for(i = 0; i  numItems; ++i)
 {
 tuple = PyTuple_GetItem(args,i);
 if(!PyArg_ParseTuple(tuple,sff,...) {
 //handle error
 Py_RETURN_NONE;
 }
 }
}

Also, you need to INCREF Py_None before you return it. Or you can use 
the macro used in the sample code above.

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


Re: From Python to c++

2006-03-21 Thread Farshid Lashkari
 Any suggestions are very welcome!

Are you allowed to use any boost libraries? If so then boost::any would 
probably help. The boost::any object can contain any object type. So you 
could have a single container that looked like the following:

std::map std::string, std::vectorboost::any  result;

Since you know the type, you would use boost::any_cast to convert it to 
that type. You can find information about it here:

http://www.boost.org/doc/html/any.html

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


Re: Passing a method indirectly

2006-03-04 Thread Farshid Lashkari
You don't need to pass the object along with the method. The method is 
bound to the object. Simply call the method by itself:

def ObjApply(method):
method()

class Test:
def test1 (self): print Hello
def test2 (self):
ObjApply(self.test1)

ta = Test ()
ta.test2 ()

If you wanted to pass an unbound method, then it would look like the 
following:

def ObjApply(object,method):
method(object)

class Test:
def test1 (self): print Hello
def test2 (self):
ObjApply(self,Test.test1)

ta = Test ()
ta.test2 ()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: when do two names cease to refer to the same string object?

2006-03-02 Thread Farshid Lashkari
I asked a similar question a few weeks ago. I think the answers I got 
will also answer your question as well. Here's a link to the thread:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/2f6f1d399ba94a7b/f564a219ffe44149?lnk=strnum=1hl=en#f564a219ffe44149

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


Re: file.read problem

2006-02-17 Thread Farshid Lashkari
 I am working on a script to get parts of raw data out of a file, and
 the data I read has to be the data written in the file without CR or
 LF.

So you just want to remove all the linefeeds? This should work then:

data = data.replace('\n','')

-Farshid

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


Re: file.read problem

2006-02-17 Thread Farshid Lashkari
 When I do this I get the first 634 bytes. I tried using the:
 f = open('myfile,'rb')
 option, but now there are a few 0x0D bytes extra in myfile. 0x0D =
 Carriage return. How can I make a program that not puts in the 0x0D
 bytes in windows.


Try opening the file in 'rbU' mode. This will use universal newline mode 
and convert all carriage returns to line feeds.

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


Re: Is empty string cached?

2006-02-16 Thread Farshid Lashkari
 A few comments (which I hope are correct, but which I hope you will read 
 then mostly ignore since you probably shouldn't be designing based on 
 this stuff anyway):

Thanks for the info Peter. My original question wasn't due to any 
observed performance problems. I was just being curious :)

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


Is empty string cached?

2006-02-15 Thread Farshid Lashkari
When I pass an empty string to a function is a new string object created 
or does python use some global pre-created object? I know python does 
this with integer objects under a certain value. For instance, in the 
following code is a new string object created for each function call?

func(0,'')
func(1,'')
func(2,'')
func(3,'')

I tried the following commands in the interactive shell:

  x = ''
  y = ''
  x is y
True
  x = 'hello'
  y = 'hello'
  x is y
True

This leads me to believe that python does reuse existing strings, but 
once the variables are removed, does the item still exist in the cache?

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


Re: How to import a module with spaces in the name

2006-02-15 Thread Farshid Lashkari
Gregory Piñero wrote:
 Let's say I have a module named Excellent Module.py

ExcellentModule = __import__('Excellent Module')

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


Re: Is empty string cached?

2006-02-15 Thread Farshid Lashkari
 It takes far too little evidence to induce belief:
 
   a = hello
   b = h+ello
   a is b
 False
   c = hello
   b is a
 False
  

I don't understand the point of your last expression. Were you intending 
this instead:

  c is a
True

However, the following commands add to my confusion:

  a = 'wtf?'
  b = 'wtf?'
  a is b
False

So how are string literals cached? Is there an explanation somewhere? Is 
it some freaky voodoo, and I should just assume that a string literal 
will always generate a new object?

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


Re: Is empty string cached?

2006-02-15 Thread Farshid Lashkari
 I really don't understand why it's so important: it's not a part of the 
 language definition at all, and therefore whatever behavior you see is 
 simply an artifact of the implementation you observe.

I guess I should rephrase my question in the form of an example. Should 
I assume that a new string object is created in each iteration of the 
following loop?

for x in xrange(100):
 func(x,'some string')

Or would it be better to do the following?

stringVal = 'some string'
for x in xrange(100):
 func(x,stringVal)

Or, like you stated, is it not important at all?

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


Re: Is empty string cached?

2006-02-15 Thread Farshid Lashkari
 It just boils down to either a LOAD_CONST vs. a LOAD_NAME - either way 
 the string isn't duplicated.

Great, that's exactly what I wanted to know. Thanks Steve!

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


Re: python spawn new process, rout stdin/out

2006-02-09 Thread Farshid Lashkari
Sounds like the popen2 module should suffice. Take a look at the 
documentation for the module here:

http://www.python.org/doc/lib/module-popen2.html

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


Re: translating PHP to Python

2006-02-05 Thread Farshid Lashkari
 Is there a simple way to get the current object's name? You would think
 __name__ would work, right? It doesn't.

className = item.__class__.__name__

 I'd like to avoid passing a reference to an object's parent in
 __init__, but is there a built in way in Python to say You, Parent
 Object, do ...stuff!

Use the super() function to access an attribute of a parent clas

class C(B):
   def meth(self, arg):
 super(C, self).meth(arg)

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


Re: Embedding Python into C/C++ applications

2006-02-03 Thread Farshid Lashkari
John Dean wrote:
 Hi
 
 Could somebody, please tell me where I can find information about embedding
 Python into a C/C++ application. The example in the docs is rather simple. I
 am looking for something a bit more complex and longer
 

Are you looking for a specific kind of example? Here is a link to a two 
part tutorial on Code Project that might help you out:

http://www.codeproject.com/cpp/embedpython_1.asp
http://www.codeproject.com/cpp/embedpython_2.asp

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


Re: would it be feasable to write python DJing software

2006-02-02 Thread Farshid Lashkari
Levi Campbell wrote:
 Hi, I'm thinking about writing a system for DJing in python, but I'm
 not sure if Python is fast enough to handle the realtime audio needed
 for DJing, could a guru shed some light on this subject and tell me if
 this is doable or if I'm out of my fscking mind?
 

What do you mean by DJing? Queueing and playing audio files? If so, 
python should work fine. Check out the PyMedia library for 
playing/mixing audio with python.

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


Re: calling a class method in a python module

2006-02-01 Thread Farshid Lashkari
 Can anybody tell me how to call f in my C code?

Assuming you already have a handle to an instance of MyClass this should 
do the trick:

PyObject *func = PyObject_GetAttrString(MyClassInst,f);
if(func) {
 PyObject *result = PyObject_CallObject(func,NULL);
 if(result) {
 //Do something with result
 Py_DECREF(result);
 }
 Py_DECREF(func);
}

Have a look in the Python/C API Reference Manual for more information.

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


Re: Having Trouble with Scoping Rules

2006-01-30 Thread Farshid Lashkari
You need to declare _expensiveObject as global inside your function. 
Whenever you assign something to a variable that resides in the global 
scope inside a function, you need to declare it as global at the 
beginning of the function. So your function should look like this

def ExpensiveObject():
 global _expensiveObject
 if not(_expensiveObject):
 _expensiveObject = A VERY Expensive object

 return _expensiveObject

The documentation will no doubtedly explain it better than I have

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


Re: A class with eventhandlers ?

2006-01-29 Thread Farshid Lashkari
It's definitely possible, here's a small example. There are probably 
better ways to do it, but I'll let you figure that out ;)

class ErrorHandler:
def __init__(self,method):
self.method = method
self.errorHook = None

def onError(self,hook):
self.errorHook = hook

def __call__(self, *args, **kwargs):
if self.errorHook:
try:
self.method(*args,**kwargs)
except Exception, e:
self.errorHook(e)
else:
self.method(*args,**kwargs)


class MyClass:
def __init__(self):
self.load = ErrorHandler(self.load)

def load(self,filename):
return self.x

def IOErrorHook(e):
print 'Caught error:',e

c = MyClass()
c.load.onError(IOErrorHook)
c.load('filename')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: exporting multiple modules from one dll?

2006-01-26 Thread Farshid Lashkari
 I have a dll that contains all kinds of services (input, audio, video, 
 etc..), and I would like to export these to Python as separate modules. 
 Now, if I call Py_InitModule with a name that's different than the dll 
 name, I get an error. So what can I do?


I believe you can export different modules from one dll, but you *MUST* 
at least export a module that has the same name as the dll. If the name 
of your dll is mymodule.dll then your init function should look like the 
following:

void initmymodule()
{
 Py_InitModule(mymodule, mymoduleMethods);
 Py_InitModule(audio, audioMethods);
 Py_InitModule(video, videoMethods);
 Py_InitModule(input, inputMethods);
}

At the python level you would have to do the following:

import mymodule #Must be import before audio,video, and input
import audio
import video
import input

I've never actually tried this, but I don't see why it wouldn't work. 
Let me know how it goes.

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


Re: generating method names 'dynamically'

2006-01-26 Thread Farshid Lashkari
 Is it possible to have method names of a class generated somehow dynamically?

If you don't know the name of the method ahead of time, how do you write 
the code for it? Do you use some dummy name? If so, once you have the 
name determined then you could use setattr to set the method name. 
Here's a simple example:

class MyClass:
 def DummyMethodName(self): pass

setattr(MyClass,'NewMethodName',MyClass.DummyMethodName)

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


Re: Executing script with embedded python

2006-01-25 Thread Farshid Lashkari
 The problem is that PyObject_CallObject always returns NULL. Is this the
 correct return value for simply executing a script, as there is no function
 return value involved?

The documentation for PyObject_CallObject states the following:

Returns the result of the call on success, or NULL on failure.

So it seems like the call is failing. My guess would be that modules are 
not callable objects. Also, this seems somewhat redundant since your 
module is effectively executed when you import it using the 
PyImport_Import function.

-Farshid

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


Re: Problems with import of modules

2006-01-23 Thread Farshid Lashkari
 How can I modify the python search-path from within the script, thus it 
 contains the doc directory?

Hi,

The sys.path variable is a list of strings that contains the current 
module search path. You can add your own path to this list:

import sys
sys.path.append('../')

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


Re: C Extended module init/cleanup

2006-01-23 Thread Farshid Lashkari
 Can C extended python modules provide any kind module destructor, so 
 that whenever the module is unloaded some cleanup is run?


I've needed the same thing before but couldn't find it. AFAIK, the best 
you can do is register an exit function that will be called when python 
exits. Here is a sample code snippet:

//Called when python exits
void CleanupModule(void)
{
 //Perform cleanup here
}


Then in your initmodule function add the following code:

//Register function to be called when python exits
Py_AtExit(CleanupModule);

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


Re: Redirecting standard out in a single namespace

2006-01-20 Thread Farshid Lashkari
Fuzzyman wrote:
 Is there another way to shadow the sys module from a single namespace ?

I've never actually tried this, but try making a copy of the sys module 
then replacing the stdout object with your own object. Then you can 
replace sys of the namespace with your custom sys module. I guess it 
would look something like this:

import mysys #My dummy sys module
import sys   #Actual sys module

#Copy sys module into dummy sys module
mysys.__dict__.update(sys.__dict__)

#Replace stdout with custom stdout
mysys.stdout = MyStdout()

#Replace sys of namespace
namespace.sys = mysys


This seems like it should work, however I don't know if copying the 
entire dictionary of one module to another is a safe thing to do.

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


Determine if object is a Bound or Unbound method

2005-07-28 Thread Farshid Lashkari
Hi,

I have an object and I want to check if it is a bound or unbound method, 
or neither. I tried using the types module, but it seems as though 
types.UnboundMethodType and types.MethodType are equal. How else can I 
determine this? BTW, I'm using Python 2.3

Thanks,

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


Re: Determine if object is a Bound or Unbound method

2005-07-28 Thread Farshid Lashkari
Grazie!

Paolino wrote:
 Farshid Lashkari wrote:
 
 Hi,

 I have an object and I want to check if it is a bound or unbound 
 method, or neither. I tried using the types module, but it seems as 
 though types.UnboundMethodType and types.MethodType are equal. How 
 else can I determine this? BTW, I'm using Python 2.3

 Thanks,

 Farshid
 
 Bound methods has an im_self attribute set to the instance binding them
 
 Ciao
 

 ___ Yahoo! Messenger: chiamate gratuite 
 in tutto il mondo http://it.beta.messenger.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find the classname of an object? (was Python Documentation)

2005-05-12 Thread Farshid Lashkari
This will get the name of an objects class

obj.__class__.__name__

This will return a tuple of its base classes

obj.__class__.__bases__

Christopher J. Bottaro wrote:
 I actually want all the parent classes too.  So if D derives off C derives
 off B derives off A, I ultimately want a tuple ('D', 'C', 'B', 'A').
 
 For those of you following the Python Documentation thread, this is a good
 example of how the PHP manual is better.  I found how to do this in a few
 seconds in PHP.  I searched the Python docs for class name, classname,
 introspection and getclass.  I looked in the Class section of the
 tutorial also and also the Programming FAQ.  The related functions
 section of the PHP manual is really helpful.  It would be cool if in the
 section for the built-in function isinstance() or issubclass() there is a
 section for related functions that would point me to getclassname(obj)
 (if it exists).
 
 Thanks for the help.
 
 -- C
 
-- 
http://mail.python.org/mailman/listinfo/python-list