Automatic keyword argument source change?

Anyone know of a Python source code utility PSU, to automatically add
keyword arguments to method calls that don't have them :


def get_total(books, binders, hinges):
return ( + - books.cost)

def print_total():
print get_total(novels, covers, brackets)



def print_total():
-- print get_total(novels, covers, brackets)
++ print get_total(books=novels, binders=covers, hinges=brackets)

Posted On: Wednesday 7th of November 2012 12:36:33 PM Total Views:  529
View Complete with Replies

Related Messages:

Re: automatically insert text in ms-word properties   (192 Views)
"gita ziabari" writes: > , > > I wanna use python to automatically insert text in ms-word properties. > Anyone could help me Why not use VBA for that work > >
Re: automatically import modules upon interpreter invocation   (228 Views)
Daniel Fetchinson wrote: > Hi folks, this seems like a very basic thing but I couldn't find a solution. > I always do the following after starting the python interpreter (on linux): > > import rlcompleter > import readline > readline.parse_and_bind("tab: complete") > > Is there a way of making python execute the above whenever it starts > up so that I don't have to type it all the time > > Cheers, > Daniel > environment variable PYTHONSTARTUP can be set to a python file that runs when you start the python interpreter - Ken
Re: Translating keywords   (169 Views)
"Gabriel Genellina" wrote in message | En Mon, 07 Apr 2008 14:59:08 -0300, Terry Reedy | escribi: | > If you want other-language keywords, you should either use a translator | > processor or an editor that will do keyword substitution. I do not know | > of | > such but I would not be surprised if there is one. I suspect this sort | > of | > thing will more likely happen with Python 3, which will allow unicode | > keywords. | | Python 3 allows for unicode identifiers, but I don'k know any plans for | using unicode keywords too. Looks funny: There are no official (PSF) plans and I expect there will be not be any for a long time if ever. My 'suspicion' was with respect to very unofficial 3rd party efforts, perhaps not even announced here in English/ascii land. My reasoning: If one is writing in ascii only, then ascii keywords and even English keywords are not so much a burden. But if one is writing comments and strings and identifiers in a different alphabet, then ascii begin to look odd and native character keywords more inviting.
RE: keyword 'in' not returning a bool?   (207 Views)
> -----Original Message----- > From: [mailtoython- >] On Behalf Of c james > Sent: Friday, February 08, 2008 12:10 PM > To: > Subject: keyword 'in' not returning a bool > > Try this > > >>> sample = {'t':True, 'f':False} > >>> 't' in sample > True > >>> type('t' in sample) > > >>> 't' in sample == True > False > > Why is this Now try > >>> bool('t' in sample) == True > True > > Can someone explain what is going on > >>> ('t' in sample) == True True It's operator precedence. 'in' has lower precedence than '=='. Therefore 't' in sample == True evaluates as 't' in (sample == True) The real question is why does 't' in (sample == True) cause an error: TypeError: argument of type 'bool' is not iterable while 't' in sample == True does not
n00b with urllib2: How to make it handle cookie automatically?   (281 Views)
Hi all, I need urllib2 do perform series of HTTP requests with cookie from PREVIOUS request(like our browsers usually do ). Many people suggest I use some library(e.g. pycURL) instead but I guess it's good practise for a python beginner to DIY something rather than use existing tools. So my problem is how to expand the urllib2 class from cookielib import CookieJar class SmartRequest(): cj=CookieJar() def __init__(self, strUrl, strContent=None): self.Request = urllib2.Request(strUrl, strContent) self.cj.add_cookie_header(self.Request) self.Response = urllib2.urlopen(Request) self.cj.extract_cookies(self.Response, self.Request) def url def read(self, intCount): return def headers(self, strHeaderName): return self.Response.headers[strHeaderName] The code does not work because each time SmartRequest is initiated, object 'cj' is cleared. How to avoid that The only stupid solution I figured out is use a global CookieJar object. Is there anyway that could handle all this INSIDE the class I am totally new to OOP & python programming, so could anyone give me some suggestions
keyword 'in' not returning a bool?   (184 Views)
Try this >>> sample = {'t':True, 'f':False} >>> 't' in sample True >>> type('t' in sample) >>> 't' in sample == True False Why is this Now try >>> bool('t' in sample) == True True Can someone explain what is going on
keyword parameter order   (165 Views)
I am looking for a way to determine the order of keyword parameters passed on to a class method. In the source code the keyword parameters are ordered, an ordering that is lost by putting them into a dictionary and then accessing them by using **kw. If I had this order (either of the keyword+value pairs or just of the keywords) I could meaningfully initialise my ordereddict implemenation (which uses Key Insertion Order or KeyValue Insertion Order). I looked at traceback (which shows this info if all the keywords are on one source line), and tracing that I found that it displays the sourcecode line based on the code-object found in the frame stack. I could persue that but I find the idea of reparsing the sourcecode kind of ugly (although doable, as the keyword are never variables, and I would not have to reevaluate the variables). I am not sure if this kind of info is available internally to the interpreter (ordereddict is in C, so I would even prefer that). Has anyone done this or anything like it I could probably compile the python interpreter to use ordereddict instead of dict and then the parser would insert the keyword parameters in specification order in the **kw ordereddict, after which iteration over parameters would be ordered. I am pretty sure though if the 10% speed overhead of the ordereddict implementation compared to dict is going to prevent people from using such an interpreter version. As an aside: I think that allowing dict to be initialised from keyword parameters (introduced in Python 2.2 IIRC) was a mistake. This kind of use of keyword parameters prevents any real keyword parameters. E.g. with 'maxsize' that restricts the dictionary size or 'unique' that would throw an Exception if an existing key gets reassigned. Anthon
Python process automatically restarting itself   (204 Views)
What is the best way for a Python process (presumed to be a script run by the interpreter binary, not embedded in some other program) to restart itself This is what I've been trying: import __main__ for path in sys.path: path += '/' + __main__.__file__ if os.access(path, os.F_OK): break else: raise Exception('WTF') #Then, something like... os.execl(sys.executable, sys.executable, path, *sys.argv[1:]) BUT! This is a multi-threaded program, and at least on OS X, trying to exec*() in a threaded process raises OSError [Errno 45] Operation not supported. So I tried having it fork, and having the child process wait for the parent process to die (in various ways) and then exec*(). That seemed to work, sort of, but the child would not be attached to the original terminal, which is a must. Any ideas
"do" as a keyword   (126 Views)
First off let me state that I really enjoy using Python. I am a 3rd year student and have been using python for 3 months, (thanks to trac!). I do not consider myself an experienced or clever programmer, but I am able to get by. Something I love about Python is that almost everything you do can be written in pseudo code then carried across into Python without a great- deal of difference. But reading through the warts and reading about a lack of "do while statements" I also started to ponder about the "'do something' if 'true' else 'do this'", and pondered if perhaps this statement could do with the including of the keyword do. It would clear up the usage of such a statement because it would read happily. Or am I making a mountain out of an ant hill
Factory function with keyword arguments   (187 Views)
I'm writing a factory function that needs to use keywords in the produced function, not the factory. Here's a toy example: def factory(flag): def foo(obj, arg): if flag: # use the spam keyword to method() return obj.method(spam=arg) else: # use the ham keyword return obj.method(ham=arg) return foo Problem: the test of which keyword to use is done every time the produced function is called, instead of once, in the factory. I thought of doing this: def factory(flag): if flag: kw = 'spam' else: kw = 'ham' def foo(obj, arg): kwargs = dict([(kw, arg)]) return obj.method(**kwargs) return foo Is this the best way of doing this Are there any alternative methods that aren't risky, slow or obfuscated Before anyone suggests changing the flag argument to the factory to the name of the keyword, this is only a toy example, and doing so in my actual code isn't practical. -- Steven.
automatically setting platform-dependent location for Distutils "install-scripts"?   (232 Views)
all, I am developing a Python-based tool that will be deployed both in a Windows and in a Linux environment, and I have a question concerning the use of the Distutils module to manage the installation of the tool in a transparent manner. A bit of background info: 1. (I am using Python version 2.5) 2. Let's assume that the tool is named "xyz" 3. It is internally partitioned into two parts: -- the front-end script that the users actually invoke, and xyzPackage -- a package containing the "guts" of the tool 4. Users do not really care where the "xyzPackage" part is installed -- and thus by default it will be installed into Python's standard "site-packages" directory. 5. However, users *do* care where the "" part is installed Now, I have created a Distutils-based "" script that looks like this: from distutils.core import setup > > setup(name='xyz', > version="1.0", > # provide other metadata, such as 'description', 'author', 'author_email', 'url', ... etc. > > packages=['xyzPackage'], > > scripts=['']) > .... that takes care of the above concerns, and also accepts a "setup.cfg" configuration file that allows the user to control into which directory to install the "" part, as follows: > > [install] > install-scripts=C:\xyzScriptDirectory > And thus, here is my problem: [1] At any given moment, the directory name specified in the above "setup.cfg" file can be either a "Windows-style" directory (as is shown above) or a "Linux-style" directory (say "/opt/xyzScriptDirectory"), but not both! [2] I would like to have a *single* "setup.cfg" file that can nevertheless be used for *both* Windows and Linux, *without* having to be edited by the user. For example, it would be really nice if I can have a customized "setup.cfg" file that looks like: > > [install] > install-scripts-Windows=C:\xyzScriptDirectory > install-scripts-Linux=/opt/xyzScriptDirectory > .... and then some part of Distutils can query "" and set the "real" 'install-scripts' option to the appropriate one of these two choices. I assume this can be done by "overriding" and customizing part of Distutils. Indeed, I have already done something similar by overriding "distutils.command.build_scripts" to use a customized "copy_scripts()" method. However, it is not clear to me in what manner I can/should override "distutils.command.install_scripts" to achieve the effect that I dee. Is this at all the way to go, or might there be a totally obvious way to do this that I am currently overlooking If anyone has similar experience in tweaking Distutils, I would be most appreciative of any advice that you can offer.
RE: Changing the names of python keywords   (243 Views)
, I on working on windows and Python 2.4. Where can I find and CHANGE python grammar. ( I just want to change the keywords ) PLEASE HELP ME SOMEBODY!!!!!! THANKS!!!!!!!!!!!!!!!!!
Changing the names of python keywords and functions   (216 Views)
, I am trying to make a program for 3D modelling with "programming".And I want make my own program commands, for example when user type code in my program: " OS"- (THIS IS MY IMAGINARY EXAMPLE OF KEYWORD), my program must write this code in some user file, but my program must read this command like: "import os".How can I do something like that Please, HELP ME somebody!!!
automatical pdf generating   (182 Views)
all, There are 50 folders in my hard driver C: C:\01.c:\02,...,c:\50 There are 4 pictures in each folder: 1.jpg,2.jpg,3.jpg,4.jpg For each folder, I want to print the 4 pictures into a single-paged pdf file (letter sized; print horizontally). together, I want to get 50 pdf files with names: 01.pdf,02.pdf,...,50.pdf. Is it possible to use Python to realized the above process I know there is a module named "reportlab". Is there any easy command in the module to do my job
Simple Python interface for making automatic phone calls   (168 Views)
The Voicent Python Simple Interface class contains the following functions. callText callAudio callStatus callRemove callTillConfirm These functions are used to invoke telephone calls from your Python program. For example, callText is used to call a specified number and automatically play your text message using text-to-speech engine. In order for this class to work, you'll need to have Voicent Gateway installed somewhere in your network. This class simply sends HTTP request for telephone calls to the gateway. Voicent has a free edition for the gateway. You can download it from More information can be found at: Thank you and have fun
A Python preprocessor that has automatic flowcharting   (167 Views)
My new non-profit web site is It's about automatic flow chart generation. I have a program that automatically draws a flow chart next to Python code so that you can see and understand the flow among the lines of Python code. I use a slightly different syntax for flow control than Python does, but the rest is regular Python. I have numerous images to illustrate this. I think it would be a new way to have code that is somewhat self-documenting. It could also help Python be somewhat self-teaching, at least with respect to structured control constructs and how they work.
keyword in package name.   (153 Views)
Everyone, I have the habit of using domain names (of either the application or company) in reverse in package names. for e.g. com.spam.app1 I've recently started a project for an indian domain (tld = .in), which leads to a package name like in.spam.app1 This causes a syntax error, as "in" is a keyword. I understand that this is an unfortunate "feature", but has anyone faced this problem before, and is there a possible workaround. P.S. this would also be a problem for the iceland domains (tld = .is). TLDs: Python Keywords:
B-Soup: broken iterator, tag a keyword?   (322 Views)
, I have the following using Beautiful Soup: soup = BeautifulSoup(data) tags = soup.find(href=re.compile("/MER_FRS_L2_Canada/MER_FRS_\S +gz")) for tag in tags: print tag['href'] print tag.parent.nextSibling.string print tag.parent.nextSibling.nextSibling.string print tag.parent.nextSibling.nextSibling.nextSibling.string print tag.parent.nextSibling.nextSibling.nextSibling.nextSibling.contents[0].string For some reason I do not understand, using 'tag' as an iterator breaks the code. Can someone tell me why reading dir(soup) did not illuminate me.
Segfault in vgetargskeywords   (160 Views)
I am using ActivePython 2.5.1 (python --version returns 'Python 2.5.1') and I am trying to embed/extend. It is segfaulting in vgetargkeywords during the call to Py_Initialize(). Now, we are using a non-standard configuration, and perhaps some explanation is in order. Here's our system config (via 'uname -a' with the hostname stripped): Linux 2.6.9-67.0.4.ELsmp #1 SMP Fri Jan 18 05:00:58 EST 2008 i686 i686 i386 GNU/Linux Or from the syslog: Linux version 2.6.9-67.0.4.ELsmp (brewbuilder@hs20- (gcc version 3.4.6 20060404 (Red Hat 3.4.6-9)) #1 SMP Fri Jan 18 05:00:58 EST 2008 I've already run into the problem linking because of the __ctype_b issue, but I think I've worked around that with '-Wl,-wrap' (at least it links). Here's the compilation command line I am doing: gcc -ggdb -O0 `python-config --includes` -o main main.c `python- config --ldflags` -Wl,-wrap,__ctype_b -Wl,-wrap,__ctype_tolower -Wl,- wrap,__ctype_toupper Where GCC is: gcc (GCC) 3.4.6 20060404 (Red Hat 3.4.6-9) And the code is just a single call to Py_Initialize(). There is the additional code to handle the wrap of __ctype_b: #include #include int main(int argc, char *argv[]) { Py_Initialize(); return 0; } __const unsigned short int **__wrap___ctype_b(void) { return __ctype_b_loc(); } __const __int32_t **__wrap___ctype_tolower(void) { return __ctype_tolower_loc(); } __const __int32_t **__wrap___ctype_toupper(void) { return __ctype_toupper_loc(); } So, after compiling, when I run it it coredumps with a segfault. Looking at the stack trace with gdb yields: GNU gdb Red Hat Linux ( Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386-redhat-linux-gnu"...Using host libthread_db library "/lib/tls/". warning: exec file is newer than core file. Core was generated by `./sharc2'. Program terminated with signal 11, Segmentation fault. Reading symbols from /lib/tls/ Loaded symbols for /lib/tls/ Reading symbols from /lib/ Loaded symbols for /lib/ Reading symbols from /lib/ Loaded symbols for /lib/ Reading symbols from /lib/tls/ Loaded symbols for /lib/tls/ Reading symbols from /lib/tls/ Loaded symbols for /lib/tls/ Reading symbols from /lib/ Loaded symbols for /lib/ #0 0x080efbe3 in vgetargskeywords (args=0x40032c5c, keywords=0x0, format=0x812bf04 "|OOOi:__import__", kwlist=0x814ff84, p_va=0xbffff1c4, flags=0) at Python/getargs.c:1382 1382 Python/getargs.c: No such file or directory. in Python/getargs.c (gdb) bt #0 0x080efbe3 in vgetargskeywords (args=0x40032c5c, keywords=0x0, format=0x812bf04 "|OOOi:__import__", kwlist=0x814ff84, p_va=0xbffff1c4, flags=0) at Python/getargs.c:1382 #1 0x080efab1 in PyArg_ParseTupleAndKeywords (args=0x40032c5c, keywords=0x0, format=0x812bf03 "s|OOOi:__import__", kwlist=0x814ff84) at Python/getargs.c:1251 #2 0x080d6551 in builtin___import__ (self=0x0, args=0x40032c5c, kwds=0x0) at Python/bltinmodule.c:44 #3 0x0808ca6b in PyCFunction_Call (func=0x40025e6c, arg=0x40032c5c, kw=0x0) at Objects/methodobject.c:77 #4 0x080634d9 in PyObject_CallFunctionObjArgs (callable=0x40025e6c) at Objects/abstract.c:1860 #5 0x080f46f7 in PyImport_Import (module_name=0x40032b38) at Python/import.c:2570 #6 0x080f5319 in PyImport_ImportModule (name=0x8122fcb "__builtin__") at Python/import.c:1966 #7 0x0806f879 in _PyExc_Init () at Objects/exceptions.c:2061 #8 0x0804d5c9 in Py_InitializeEx (install_sigs=1) at Python/ pythonrun.c:228 #9 0x0804f43d in Py_Initialize () at Python/pythonrun.c:321 #10 0x0804d2c9 in main (argc=1, argv=0xbffff474) at main.c:22 Any ideas what is causing this problem It appears to be while importing the __builtin__ package, but beyond that I'm not sure.
cjson 1.0.5 keyword argument   (365 Views)
I have installed cjson 1.05 in Fedora 8 (python 2.5.1). The cjson home page shows a keyword argument "encoding". When i use it i get an error: >>> cjson.encode('', encoding='utf8') Traceback (most recent call last): File "", line 1, in TypeError: encode() takes no keyword arguments What am i missing There is no mail list for cjson.