Using eval and exec, how to write an anonymous function? [closed] - python-3.x

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
>>> compile("""
def some_function(x):
return x+2
some_function""",'compiled function','single')
Traceback (most recent call last):
File "<pyshell#3>", line 4, in <module>
some_function""",'compiled function','single')
File "compiled function", line 4
some_function
^
SyntaxError: unexpected EOF while parsing

If you want to compile a multi-statement string with compile, single should be exec. Also, after you compile the code, you have to execute it and capture the globals in order to access the created function:
def anonymous(code):
# To fix the indentation
fixed_code = '\n'.join(line[4:] for line in code.splitlines())
_globals = {}
exec(compile(fixed_code, '<string>', 'exec'), _globals)
if 'f' not in _globals:
raise ValueError('You must name your function "f"')
return _globals['f']
anonymous('''
def f(x):
return x + 2
''')(12)

Question is not very clear, but is this the example you want?
>>> c=compile('''\
... def some_function(x):
... return x+2
... print(some_function(5))
... ''','<string>','exec')
>>> exec(c)
7
>>> c=compile('7+2','<string>','eval')
>>> eval(c)
9

Related

In name == 'main', why is variables shared in class? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Well, I just noticed that variables in if name == 'main': are shared to the classes in the same file - why is this? I don't recall having this issue in python2...
class A:
def __init__(self, b):
self.b = b
def func_a(self):
return d
if __name__ == '__main__':
classA = A(1)
d = 2
print(classA.func_a())
prints out 2.
What's the reasoning?
this definitely also happens in python2
and is very simple: declaring variables outside of functions/classes makes them global and when python searches for variables with the name d it doesn't find it in the local scope but it does find the global variable

AttributeError: 'DataFrame' object has no attribute 'groupyby' [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Having used pandas for a long time, this is the first time I got an error as shown in the title of this question and I'm stuck because I don't see any reason why the DataFrame would not have the groupby function "available." Already reinstalled pandas, even looked in the code that is being used (groupby is defined in the core modules).
This is what I'm doing, the error is shown below:
def _bin_by_answer(row):
collocated_answer = row['colname']
if collocated_answer <= -1:
return -1
elif collocated_answer >= 1:
return 1
else:
return 0
df = pd.read_pickle(somepath)
df['binned'] = df.apply(func=lambda row: _bin_by_answer(row), axis=1)
df_sampled = df.groupyby(by='binned', group_keys=False).apply(lambda grp: grp.sample(n=50))
Here is the error:
Traceback (most recent call last):
File "/Users/felix/IdeaProjects/cope/ann4class/exportfromaestoretomturk.py", line 858, in <module>
process_and_export_ps2_inductive()
File "/Users/felix/IdeaProjects/cope/ann4class/exportfromaestoretomturk.py", line 786, in process_and_export_ps2_inductive
df_sampled = df_results.groupyby(by=COL_ANSWER1_COLLOCATED_MAJORITY, group_keys=False).apply(
File "/Users/felix/anaconda3/envs/cope/lib/python3.7/site-packages/pandas/core/generic.py", line 5179, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'groupyby'
As suggested by ddoGas, the cause of this error was a typo. So, I guess the general answer would be: In case you're reading this question because you're running into a similar problem, double check that you wrote the function name correctly.

TypeError: index() takes 2 positional arguments but 3 were given [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm unable to understand what triggers the below Error.
This is the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File line 26, in print_sel
dob.index(INSERT, cal.selection_get())
TypeError: index() takes 2 positional arguments but 3 were given
This is my code:
def calendar():
def print_sel():
dob.index(INSERT, cal.selection_get())
top = Toplevel(root)
top.title("Select Registration Date")
cal = Calendar(top, font="Arial 14", selectmode='day', locale='en_US',
cursor="hand1", year=2019, month=4, day=4)
cal.pack(fill="both", expand=True)
Button(top, text="ok", command=print_sel).pack()
dob=Entry(Registration_Frame,style='TEntry')
dob.grid(row=3,column=1,columnspan=2,sticky=NSEW)
Button(Registration_Frame, text='Select',command=calendar,width=5,style='TButton').grid(row=3,column=3)
You confused the .insert() method with index(); the latter only takes a single argument, and would move longer text within the entry box to show the character at the given index to be the left-most visible character.
Just replace .index() with .insert():
dob.insert(INSERT, cal.selection_get())

Manipulating the order of items in a list [duplicate]

This question already has answers here:
How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)?
(11 answers)
Closed 4 years ago.
I am a not an experienced programmer so please bear with me.I have been trying to solve this problem for hours to no avail. I would really appreciate a solution to my problem.
Create a program that will:
reverse the order of a list if the list consists of integers alone
Will convert the list items to uppercase if the list contains words
only.
Will return the same list if the list members don’t satisfy either of
these two criteria
Edit: This question is a duplicate
Here is my test code:
import unittest
import switchreverse
class Reverser(unittest.TestCase):
def test_Reverse(self):
word_lists = [1,2,3,4,5]
for e in word_lists:
if type(0):
assert word_lists.reverse()
if type(''):
assert word_lists.upper()
else:
return word_lists
if __name__ == '__main__':
unittest.main()
Here is the code being tested:
def Switchreverser():
word_lists = [1,2,3,4,5]
for e in word_lists:
if type(0):
word_lists.reverse()
elif type(''):
word_lists.upper()
else:
return word_lists
Here is the error I am recieving:
F
======================================================================
FAIL: test_Reverse (__main__.Reverser)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_switchreverse.py", line 8, in test_Reverse
assert word_lists.reverse()
AssertionError
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
list.reverse modifies list in-place and returns None, so assert list.reverse() is the same as assert None which obviously raises AssertionError.
Unrelated, but if type(0) and if type('') are not going to check the type of the lists' elements. Instead, you should be doing if all(isinstance(element, int) for element in list).

unexpected results while copying file using shutil [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I want to copy one file to another. From the accepted answer of this thread, I have done:
def fcopy(src):
dst = os.path.splitext(src)[0] + "a.pot"
try:
shutil.copy(src, dst)
except:
print("Error in copying " + src)
sys.exit(0)
and using it as:
print(atoms)
for q in range(0, len(atoms), 2):
print(type(atoms[q]))
print(atoms[q], fcopy(atoms[q]))
This is quite a few check down inside the code, but I expect that does not matter as long as it finds atoms[q]. But the result I am getting is:
['Mn1.pot', 'Mn2.pot'] <= result of print(atoms)
<class 'str'> <= result of type(atoms)
Mn1.pot None <= result of print(atoms,fcopy(atoms)).
['Mn3.pot', 'Mn4.pot']
<class 'str'>
Mn3.pot None
['Mn5.pot', 'Mn6.pot']
<class 'str'>
Mn5.pot None
['Mn7.pot', 'Mn8.pot']
<class 'str'>
Mn7.pot None
Where I was expecting the print(atoms[q], fcopy(atoms[q])) to give me Mn1.pot Mn1a.pot
I am still a beginner in python, so it will be great if someone can show me what's going wrong here.
You are not getting an error -- if you did you would see the Error in copying message printed.
The part you need to know is that every Python function returns a value. If you do not tell Python what value to return, Python returns None.
So if you want the destination file to be returned to the caller, you have to do it yourself:
def fcopy(src):
dst = os.path.splitext(src)[0] + "a.pot"
try:
shutil.copy(src, dst)
return dst # this line should be added
except:
print("Error in copying " + src)
sys.exit(0)

Resources