Assignment within expression in Python - python

In Java, if I want to increase a variable A, and set B equal to C, I can do it one statement as follows:
B = C + A - A++;
Python, unfortunately, does not support assignment within literals. What is the best way to mimic this kind of behavior within the language of Python? (with the intention of writing code in as few statements as possible)
Let me set something straight: I am not interested in writing code that is readable. I am interested in writing code with as few statements as possible.
One trivial example of one case where this would work would be to write a class that holds an int and has methods such as plus_equals, increment, etc.

In the global namespace, you can do something really ugly like this:
B = globals().__setitem__('A', A + 1) or C
Unfortunately for you (and probably fortunately for the person who has to read the code after you've written it), there is no analogous way to do this with a local variable A.

Let me set something straight: I am not interested in writing code that is readable. I am interested in writing code with as few statements as possible.
Well, if that's your goal, wrap your entire program in a giant exec:
exec """
<your program here>
"""
Bam, one statement.

Related

Why must a variable be declared a global variable before it gets assigned?

Why do we have to do this:
global x
x = "Hello World!"
When this is more readable:
global x = "Hello World"
Why is this, is there a reason behind it?
The goal of Python is to be as readable as possible. To reach this goal the user must be forced act in a clear defined way - e.g. you must use exactly four spaces. And just like this it defines that the global keyword is a simple statment. This means:
A simple statement is comprised within a single logical line.
Simple Statements
And
Programmer’s note: the global is a directive to the parser. It applies only to code parsed at the same time as the global statement.
The global statement
If you would write this:
global x = 5
You would have two logical operations:
Interpreter please use the global x not a local one
Assign 5 to x
in one line. Also it would seem like the global only applies to the current line, and not to the whole code block.
TL;TR
It's to force the user to write better readably code, which is splitted to single logical operations.
The document writes that
Names listed in a global statement must not be used in the same code block textually preceding that global statement.
CPython implementation detail: The current implementation does not enforce the latter two restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.
As for the readability question, I think the second one seems like a C statement. Also it not syntactically correct
I like to think it puts your focus squarely on the fact that you are using globals, always a questionable practice in software engineering.
Python definitely isn't about representing a problem solution in the most compact way. Next you'll be saying that we should only indent one space, or use tabs! ;-)

python fast writing of a variables name and value

I am porting some code from matlab to python and i see that I miss fast variable content inspection and printing of the matlab (in scripts) like shown below.
a=6
a =
6
Same thing in python:
a=6 ; print "a = \n",a
a =
6
In a matlab script if you write an assignment like shown above, without a semicolon at the end, it prints just like that. You can write the whole script like that, and later shutdown all those lines with semicolons. It is very helpful for early debugging purposes.
Just now, I scanned all lines with assignments, and put prints like
; print "a", a
at the end of them. I immediately saw the problem with the code.
Is there a way to type less for this purpose?
The ipython (or plain python) interactive interpreter already shows you the value of anything you type into it.
The only reason you don't see anything for a=6 is that, in Python, assignment is a statement, not an expression, and therefore it doesn't have a value.
But if you just type a, that's an expression, with a value, and it will show you the value:
In [8]: a=6
In [9]: a
Out[9]: 6
If that's not good enough, and you want it to automatically show you the name and value for any assignment statement… that's not impossible, but it's much harder than it's worth.

Python 'if' within assignment acceptable?

Friday I had a discussion with someone about the following contruction:
class C(....
c = C()
d = C()
...
(c if some_boolean else d).some_function_of_class_C()
Is this kind of if statement acceptable/encouraged?
The problem is that a lot of people I work with have C experience but not that much Python experience and are not used to such statement (same like list comprehension).
However, Python is not C and I think the advantages of the Python language should be used.
Or not?
(btw, I use normal function names and variable names but it is just for the sake of this example to keep it sample. Also I do not only call f() but some more functions (like f().g() which I woud have to repeat completely in that case.
There's nothing technically wrong with your code, but it is a little odd and surprising to see code like that.
Splitting your statement into two separate statements improves the readability:
c = c1 if some_boolean else c2
c.some_function_of_class_C()
The terrible variable names you have chosen still make it look awful. But changing the variable names also helps to improve the readability:
vehicle = plane if distance > 1000 else car
vehicle.travel()
That is a lot more readable than what you originally proposed, in my opinion, and it only took a very small change.
It is syntactically and semantically valid, but it certainly isn't Pythonic. Consider using the Strategy pattern instead.
Writing code in one language but using the styles and limitations of another language are never a good idea in the long run. Your python code should always be pythonic.
That said, make sure your code is readable assuming that the person reading the code understands python syntax, or at least enough to google the rest.

Creating a function object from a string

Question: Is there a way to make a function object in python using strings?
Info: I'm working on a project which I store data in a sqlite3 server backend. nothing to crazy about that. a DAL class is very commonly done through code generation because the code is so incredibly mundane. But that gave me an idea. In python when a attribute is not found, if you define the function __getattr__ it will call that before it errors. so the way I figure it, through a parser and a logic tree I could dynamically generate the code I need on its first call, then save the function object as a local attrib. for example:
DAL.getAll()
#getAll() not found, call __getattr__
DAL.__getattr__(self,attrib)#in this case attrib = getAll
##parser logic magic takes place here and I end up with a string for a new function
##convert string to function
DAL.getAll = newFunc
return newFunc
I've tried the compile function, but exec, and eval are far from satisfactory in terms of being able to accomplish this kind of feat. I need something that will allow multiple lines of function. Is there another way to do this besides those to that doesn't involve writing the it to disk? Again I'm trying to make a function object dynamically.
P.S.: Yes, I know this has horrible security and stability problems. yes, I know this is a horribly in-efficient way of doing this. do I care? no. this is a proof of concept. "Can python do this? Can it dynamically create a function object?" is what I want to know, not some superior alternative. (though feel free to tack on superior alternatives after you've answered the question at hand)
The following puts the symbols that you define in your string in the dictionary d:
d = {}
exec "def f(x): return x" in d
Now d['f'] is a function object. If you want to use variables from your program in the code in your string, you can send this via d:
d = {'a':7}
exec "def f(x): return x + a" in d
Now d['f'] is a function object that is dynamically bound to d['a']. When you change d['a'], you change the output of d['f']().
can't you do something like this?
>>> def func_builder(name):
... def f():
... # multiline code here, using name, and using the logic you have
... return name
... return f
...
>>> func_builder("ciao")()
'ciao'
basically, assemble a real function instead of assembling a string and then trying to compile that into a function.
If it is simply proof on concept then eval and exec are fine, you can also do this with pickle strings, yaml strings and anything else you decide to write a constructor for.

Is there a way to convert code to a string and vice versa in Python?

The original question was:
Is there a way to declare macros in Python as they are declared in C:
#define OBJWITHSIZE(_x) (sizeof _x)/(sizeof _x[0])
Here's what I'm trying to find out:
Is there a way to avoid code duplication in Python?
In one part of a program I'm writing, I have a function:
def replaceProgramFilesPath(filenameBr):
def getProgramFilesPath():
import os
return os.environ.get("PROGRAMFILES") + chr(92)
return filenameBr.replace("<ProgramFilesPath>",getProgramFilesPath() )
In another part, I've got this code embedded in a string that will later be
output to a python file that will itself be run:
"""
def replaceProgramFilesPath(filenameBr):
def getProgramFilesPath():
import os
return os.environ.get("PROGRAMFILES") + chr(92)
return filenameBr.replace("<ProgramFilesPath>",getProgramFilesPath() )
"""
How can I build a "macro" that will avoid this duplication?
Answering the new question.
In your first python file (called, for example, first.py):
import os
def replaceProgramFilesPath(filenameBr):
new_path = os.environ.get("PROGRAMFILES") + chr(92)
return filenameBr.replace("<ProgramFilesPath>", new_path)
In the second python file (called, for example, second.py):
from first import replaceProgramFilesPath
# now replaceProgramFilesPath can be used in this script.
Note that first.py will need to be in python's search path for modules or the same directory as second.py for you to be able to do the import in second.py.
No, Python does not support preprocessor macros like C. Your example isn't something you would need to do in Python though; you might consider providing a relevant example so people can suggest a Pythonic way to express what you need.
While there does seem to be a library for python preprocessing called pypp, I am not entirely familiar with it. There really is no preprocessing capability for python built-in. Python code is translated into byte-code, there are no intermediate steps. If you are a beginner in python I would recommend avoiding pypp entirely.
The closest equivalent of macros might be to define a global function. The python equivalent to your C style macro might be:
import sys
OBJWITHSIZE = lambda x: sys.getsizeof(x) / sys.getsizeof(x[0])
aList = [1, 2, 4, 5]
size = OBJWITHSIZE(aList)
print str(size)
Note that you would rarely ever need to get the size of a python object as all allocation and deletion are handled for you in python unless you are doing something quite strange.
Instead of using a lambda function you could also do this:
import sys
def getSize(x):
return sys.getsizeof(x) / sys.getsizeof(x[0])
OBJWITHSIZE = getSize
aList = [1, 2, 4, 5]
size = OBJWITHSIZE(aList)
print str(size)
Which is essentially the same.
As it has been previously mentioned, your example macro is redundant in python because you could simply write:
aList = [1, 2, 4, 5]
size = len(aList)
print str(size)
This is not supported at the language level. In Python, you'd usually use a normal function or a normal variable where you might use a #define in C.
Generally speaking if you want to convert string to python code, use eval. You rarely need eval in Python. There's a module somewhere in the standard library that can tell you a bit about an objects code (doesn't work in the interp), I've never used it directly. You can find stuff on comp.lang.python that explains it.
As to 'C' macros which seem to be the real focus of your question.
clears throat DO NOT USE C MACROS IN PYTHON CODE.
If all you want is a C macro, use the C pre processor to pre process your scripts. Duh.
If you want #include, it's called import.
If you want #define, use an immutable object. Think const int foo=1; instead of #define foo 1. Some objects are immutable, like tuples. You can write a function that makes a variable sufficiently immutable. Search the web for an example. I rather like static classes for some cases like that.
If you want FOO(x, y) ... code ...; learn how to use functions and classes.
Most uses of a 'CPP' macro in Python, can be accomplished by writing a function. You may wish to get a book on higher order functions, in order to handle more complex cases. I personally like a book called Higher Order Perl (HOP), and although it is not Python based, most of the book covers language independent ideas -- and those ideas should be required learning for every programmer.
For all intents and purposes the only use of the C Pre Processor that you need in Python, that isn't quite provided out of box, is the ability to #define constants, which is often the wrong thing to do, even in C and C++.
Now implementing lisp macros in python, in a smart way and actually needing them... clears throat and sweeps under rug.
Well, for the brave, there's Metapython:
http://code.google.com/p/metapython/wiki/Tutorial
For instance, the following MetaPython code:
$for i in range(3):
print $i
will expand to the following Python code:
print 0
print 1
print 2
But if you have just started with Python, you probably won't need it. Just keep practicing the usual dynamic features (duck typing, callable objects, decorators, generators...) and you won't feel any need for C-style macros.
You can write this into the second file instead of replicating the code string
"""
from firstFile import replaceProgramFilesPath
"""

Categories

Resources