is it possible in Python to modify, or - at least - deny of execution builtin functions? I need, for educational purpose, to make sure that strings split is unavailable.
For example, I want, if call
'a,b,c'.split(',')
to throw exception or be returned inputed string.
I want to force someone to write own version of that function. Is it possible?
Thanks in advance!
Built-in types (str in your case) and methods cannot be monkey-patched, since they are implemented in C (for cpython implementation).
However, you can define a subclass and redefine the method:
>>> class Mystr(str):
... def split(self, *args):
... raise Exception("Split is not defined")
...
>>> Mystr("test").split(",")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in split
Exception: Split is not defined
Related
this is my code
import requests
r = requests.get('https://www.reddit.com/r/Art.json').json()
print(r['data'])
this code sometimes work but sometimes get fail
Exception is
Traceback (most recent call last):
File "c:/Users/SAMET/Desktop/python/a.py", line 5, in <module>
print(r['data'])
KeyError: 'data'
You must use r.data. r['data'] could work in Javascript, but in Python you can't access objects as dictionaries.
I have problems calling the help function on the pd.read_csv()
pandas is already imported as pd
import pandas as pd
help(pd.read_csv())
and I get
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
help(pd.read_csv())
TypeError: parser_f() missing 1 required positional argument: 'filepath_or_buffer'
What is wrong with my help call?
in help(pd.read_csv()) you first called pd.read_csv() (cause of the parenthesis) so the interpreter was expecting an argument for, to execute it and return its result and pass it as argument to help.
The help function accepts functions as arguments so to show help execute help(pd.read_csv).
pd.read_csv is the function, pd.read_csv() is a call to that function.
Quite simply: don't call the object you want help on. Here:
help(pd.read_csv())
The parents after pd.read_csv are the function call operator. You don't want to call this function, you want to pass it as argument to help(), ie:
help(pd.read_csv)
I have code that sets up an environment for running and logging scientific experiments. Some of the initial setup involves using the built in input() method to query the user for values. I keep getting a I/O operation on closed file error whenever I try to call input however.
Code flow: Control.py calls Analyzer.py which calls a specific method in Prompts.py (the code for which is below).
def prompt_instruments(message):
res = input(message) # query user with arg message
print("done")
if '.' in res:
print("User input not cool. Use comma-separated values.")
return None # to continue prompting
...
I have searched all over the internet and have been unable to find anything remotely related. Thank you so much!!
The code you posted seems ok, and the error is probably in one of your other files.
The input() function uses sys.stdout to display the prompt text, and sys.stdin to get the user's input text.
The error message you get is probably caused by one of these files being closed, e.g.:
>>> import sys
>>> input('test: ')
test: hello
'hello'
>>> sys.stdin.close()
>>> input('test: ')
test: Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
or:
>>> import sys
>>> input('test: ')
test: hi
'hi'
>>> sys.stdout.close()
>>> input('test: ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
I can't tell you exactly where to fix this issue, but look for things that might close one of these file, either directly or indirectly (e.g. context manager).
I am trying to save some copy-paste while defining my buttons and other things in my main class through eval(). I know eval() is supposed to be handled with care, but here I give the commands within my code. Here's the code that creates an error:
class MyApp(QMainWindow):
def __init__(self):
[...]
Schaltpunkte=["Aussen1","Innen1","Innen2","Innen","Alle"]
for Schaltpunkt in Schaltpunkte:
eval("self.ui.Button_"+Schaltpunkt+"Laden.clicked.connect(lambda: self.ladeZeitschaltung("+Schaltpunkt+"))")
The error I get once I clicked the button:
Traceback (most recent call last):
File "<string>", line 1, in <lambda>
NameError: name 'self' is not defined
I had this idea, because eval() works very well inside another function:
Programm = eval("self.ui.Box_"+Schaltpunkt+"Programm.value()")
Does someone have any advice? Or is it simply wrong to connect buttons with actions through such code? Thanks for your help!
Your lambda function is not aware of self.
Try to define a symbol table mentioning self, and give it to eval():
symbols = {"self": self}
eval("lambda x: self.foo(x)", symbols)
This seems to work in python 2.7, but not python 3. Is there an easy way to make a set a list in python 3 that I am missing? Thanks in advance.
mylist = [1,2,3,4,5]
list(set(mylist))
#Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
#TypeError: 'list' object is not callable
Sorry if this has been asked before, I did a quick search and didn't see an answer specific to python3.
list(set(...)) works fine. The error indicates the 3.x version of the code has a variable called list or set, shadowing the built-in function. Perhaps you renamed mylist to list? Rest assured, that mistake would provoke the exact same error message in Python 2.