This question already has answers here:
Can you add new statements to Python's syntax?
(13 answers)
Closed 2 months ago.
Not sure how to explain, I mean statemtents like:
for i in l:
if a==b:
def x():
lambda x:
class spam:
while True:
basically those control statements that end with :
can I create novel ones? (like in snakemake that has a long list of new control statements)
I tried reading documentation, but could not find anything useful.
I just want to make some tools to help develop rules for snakemake.
I am currently using this:
class SM(object):
def __init__(self,**xargs):
self.items = xargs
def __getattribute__(self,attr):
return object.__getattribute__(self, "items")[attr]
input = SM(genome="Genome/genome.fa",
table="rmats/binding_strength.maxent.CLIP.csv")
table = pd.read_csv(input.table,index_col=0)
In that example I can use the class SM to emulate all the input, output, wildcard... then I can just move the code into its rule in the Snakefile without needing to manually edit all the inputs/wildcards/outputs...
However, I will still need to write the "input:".
Is there a way I could make:
input:
table="table.csv"
do
input=SM(table:"table.csv")
#or input=SM(**xargs)
Sorry, but no can do...You would have to modify the language implementation itself (the interpreter actually). When you are programming you are bound by the syntax of the language, you cannot modify the syntax "on the fly". It's not the same as e.g. defining functions, classes and whatnot.
Take a look at these:
Can you add new statements to Python's syntax?
How to make custom reserved keywords in python3
Here's the most comprehensive answer to this kind of questions imho:
https://stackoverflow.com/a/9108164/15923186
Related
This question already has answers here:
What is a clean "pythonic" way to implement multiple constructors?
(15 answers)
Closed 4 years ago.
I am writing some genetic algorithms in python. Currently I was looking at a book that has java code, so but eventually I am trying to write my own Adaptive Genetic algorithm to optimize neural network parameters and layers, and all my neural network code is in python using keras...so I am just writing my own python code that is equivalent to the books java code.
The problem I am having with the way I have it set up currently, is that the constructor always initializes the object to the constructor in the first statement.
From what I have seen from other questions similar to this, you can use classmethods to do this...and you call also do something with ...isinstanceOf method...and you can do something with init method *args and **kwargs...and I thought you could do something with NoneType parameters which is what I am trying to do...but I have been messing with it on and off and cannot seem to get it to work without adding additional boolean arguments which I would prefer not to do.
What are peoples preferred methods to solving the multiple constructor problem, and can you do it the way I am trying to?
An example of where I am trying to use multiple constructors.
class Individual(object):
#Object Initialisation-->Generally called a constructor
#In python, a variable prefixed with _ is effectively private
def __init__(self, chromosome, chromosomeLength, bool1):
if(chromosomeLength is not None and bool1==False):
self.chromosomeLength = chromosomeLength
self.fitness = -100
self.chromosome = np.empty(chromosomeLength)
for gene in range(self.chromosomeLength):
if(0.5 < np.random.randint(2)):
#self.setGene(gene,1)
#cls.chromosome[gene] = 1
self.chromosome[gene] = 1
else:
#self.setGene(gene,0)
#cls.chromosome[gene] = 0
self.chromosome[gene] =0
elif(chromosome is not None and bool1 ==True):
self.chromosome = chromosome
self.fitness = -1
print ("All variable initialized")
Thanks,
Matt
You could probably use factory functions (or methods, if you like to have them in your class) to construct your objects from different sets of variables:
For instance (pseudocode to illustrate the idea)
from_chromosomes(chromosomes):
parse_chromosomes
return Individual(*args, **kwargs)
from_ancestors(parents):
parse_parents_genes
return Individual(*args, **kwargs)
(...)
This can be coupled with the use of default values.
This question already has answers here:
Running exec inside function
(3 answers)
Creating dynamically named variables in a function in python 3 / Understanding exec / eval / locals in python 3
(2 answers)
Closed 4 years ago.
EDIT: This question is NOT ANSWERED BY THE LINKS ABOVE that a mod added. As I said before in a comment, Python 3 brought changes, and the examples given in those answers were for Python 2. If I compile those in my Python 3 environment, I get the same error as here.
Consider
str = "x = [113, 223]"
exec(str)
print(x[0]) #113
This works perfectly. But if I want this code to be executed in a function, it returns an error NameError: name 'x' is not defined. Here's a minimal working example:
def some_code():
str = "x = [1, 2]"
exec(str)
print(x)
some_code()
What is going on here?
I need a solution to
use exec inside the function (because ultimately its a tkinter function -see the first edit history of this question- and I'm reading this from a file that should be executed
I would like to easily be able to refer to x, because I will need to do that in a lot of places. So using a long line of code to refer to x will be cumbersome.
Naively moving the relevant code to first level scope solved it.
string = "x = [113, 223]"
exec(string)
def some_code():
print(x[0]) #113
Another approach: I started toying around with exec() more and from what I can see exec() writes its results (in this case x) into the locals() and globals() builtin dictionaries. Therefore, the following is another solution to the problem, but it seems rather hacky:
def some_code():
string = "x = [113, 223]"
exec(string)
print(locals()['x'][0]) #113
some_code()
In the same manner, you can define your own dictionary for use instead of locals() where exec() stores x, which in my opinion is much cleaner:
exec_results = {}
def some_code():
string = "x = [113, 223]"
exec(string, None, exec_results)
print(exec_results['x'][0]) #113
some_code()
I highly discourage using exec() for really simple cases such as this, but if you wish to use it in the future, I highly suggest checking out other threads on the same topic that were created prior to this question, such as running-exec-inside-function and globals and locals in python exec(). Check out the Python docs on exec() to read more about exec() as well.
This question already has answers here:
How do I check if a variable exists?
(14 answers)
Closed 6 years ago.
Is there something like function_exists in PHP for Python3? I am implementing something that allows users (through some web UI) to define simple rules in JSON as follows (in some weird lisp-like structure):
["_and", ["_tautology"], ["tautology"]]
and would like to turn that into a python statement, for instance these functions
import operator
from functools import reduce
def _and(*args):
return lambda context: reduce(operator.and, [arg(context) for arg in args], True)
def _tautology(*_):
return lambda *__: True
by turning that original JSON rule into
_and(_tautology(), _tautology())
Just out of curiousity, is ast made for this kind of task? I did this once before but I am looking for something that is scalable. Because what I did before this was practically maintaining a dictionary like follows
mapping = {'_and': _and}
and the list would keep growing, and that results in more code typed to describe what the string value means, instead of implementing them. Or I should have used another rule engine? Because one of the rule would look like
["_and", ["_equals", "fieldA", "some_value"],
["_equals", "fieldB", "some_other_value"]]
Assuming _equals is
def _equals(field_name, value):
return lambda context: context[field_name] == value
so that the rule is expanded to
_and(_equals('fieldA', 'some_value'),
_equals('fieldB', 'some_other_value'))
TL;DR
Main Question: is there something like function_exists for Python3, is ast suitable for this?
Secondary Question: should I use some sort of rule engine instead?
Regarding the duplicate question report No, I am not checking if a variable exists. I want to know if there is a function that has the same name, as a string value. For example, if I have a string '_and' I want to know if there is a function named _and, not trying to figure out whether this identifier _and is actually a function.
As Morton pointed out, you could use globals() and locals() to fetch a variable using a string containing the name.
In [32]: a = 1
In [33]: def b():
c = 2
print(globals()['a'])
print(globals()['b'])
print(locals()['c'])
....:
In [34]: b()
1
<function b at 0x7f425cae3ae8>
2
But! For your task I would recommend using a decorator that registers your functions to a mapping automatically.
_mapping = {}
def register(f):
_mapping[f.__name__] = f
return f
#register
def _and(*args):
return lambda context: reduce(operator.and_,
[arg(context) for arg in args], True)
#register
def _tautology(*_):
return lambda *_: True
and so your function_exists would be just
_mapping[key]
AST is suitable for inspecting syntax trees generated from parsed python source, modifying existing syntax trees and generating new ones and transpiling to python from a different language by generating syntax trees from it (to name a few uses). So in a way yes, you could generate AST from your JSON and compile that. I believe that is actually what Hy does, though not from JSON, but full blown lisp syntax.
This question already has an answer here:
is there a pass statement in Lua like in python
(1 answer)
Closed 8 years ago.
I've recently started learning Lua. The only other programming language I have some experience in is Python. In Python there is the "pass" function that does nothing. I was wondering what the equivalent (if any) of this would be in Lua.
In Python, pass is an important placeholder for incomplete code. It must exist because the syntax demands code to be present in some circumstances where you just want to declare a function or a if statement, a loop or whatever, but leave it open for future development while making the code compilable.
def myfunction(a, b, c):
pass # im doing this later
In Lua however this is not necessary. It is perfectly fine to end an if or a function without including any code. There is no need to exist a pass in Lua.
function myfunction(a, b, c)
-- im doing this later
end
Leave your conditional empty by doing this
if <condition> then end
This question already has answers here:
How to avoid explicit 'self' in Python?
(11 answers)
python self-less
(3 answers)
Closed 9 years ago.
I am writing a program to simulate a small physical system and have become more and more annoyed as I write things like this:
K = 0.5 * self.m * self.v**2
In the case above, the equation is short and pretty understandable, but I have situations in which there is so much self that the whole thing ends up looking like a mess. I am aware that python always requires self to refer to class members, but is there a way to to make the code not look like a mosaic of self's?
EDIT: I usually do things such as:
var = self.var
and keep on using var instead of self.var. Later I do:
self.var = var
but this seems really stupid. What would be the pythonic way to solve this problem?
For messy parts I'd use Python modules and "module-level variables" instead of classes.
If all you want to do is save some keystrokes, you can always rename self to s:
class MyClass(object):
def kinetic_energy(s): # use s instead of self for brevity
return 0.5 * s.m * s.v**2
This saves you 3 characters per use of self. This goes against the standard convention, but nothing is stopping you from doing this. I would advice against doing this in general code, but it might be justified if it makes some very long formulas more readable. Do mention the unusual choice in a comment, in case anyone else has to read your code when you are long gone.
I guess it's possible to use some black magic in Python and come up with a context manager, which will take an object and put all its attribute in the context's locals(), and assign it back to object in the __exit__ function.
Found this https://code.google.com/p/ouspg/wiki/AnonymousBlocksInPython which may help.