I want to build a function for following code:
PlayDirection_encoder = LabelEncoder()
train["PlayDirection"] = direction_encoder.fit_transform(train["PlayDirection"])
train.PlayDirection.unique()
That's my current function:
def object(category):
%s = Label_Encoder() % (category + "_encoder")
train[category] = %s.fit_transform(train[category]) %(category + "_encoder")
len(train.category.unique())
object("PlayDirection")
UsageError: Line magic function `%s` not found.
I am running my code on Kaggle's server.
Do you know how to solve this problem?
calling function an object is really really bad idea. It's a reserved word in Python, so it might break everything in your code.
what do you want to achieve? your problem is not clear
Related
I am trying to execute the command abs.__ doc__ inside the exec() function but for some reason it does not work.
function = input("Please enter the name of a function: ")
proper_string = str(function) + "." + "__doc__"
exec(proper_string)
Essentially, I am going through a series of exercises and one of them asks to provide a short description of the entered function using the __ doc__ attribute. I am trying with abs.__ doc__ but my command line comes empty. When I run python in the command line and type in abs.__ doc__ without anything else it works, but for some reason when I try to input it as a string into the exec() command I can't get any output. Any help would be greatly appreciated. (I have deliberately added spaces in this description concerning the attribute I am trying to use because I get bold type without any of the underscores showing.)
As a note, I do not think I have imported any libraries that could interfere, but these are the libraries that I have imported so far:
import sys
import datetime
from math import pi
My Python version is Python 3.10.4. My operating system is Windows 10.
abs.__doc__ is a string. You should use eval instead of exec to get the string.
Example:
function = input("Please enter the name of a function: ")
proper_string = str(function) + "." + "__doc__"
doc = eval(proper_string)
You can access it using globals():
def func():
"""Func"""
pass
mine = input("Please enter the name of a function: ")
print(globals()[mine].__doc__)
globals() return a dictionary that keeps track of all the module-level definitions. globals()[mine] is just trying to lookup for the name stored in mine; which is a function object if you assign mine to "func".
As for abs and int -- since these are builtins -- you can look it up directly using getattr(abs, "__doc__") or a more explicit: getattr(__builtins__, "abs").__doc__.
There are different ways to lookup for a python object corresponding to a given string; it's better not to use exec and eval unless really needed.
I've written some code
for i in range(0, b):
for g in range(1, b+1):
if i+1==g:
a = f'''r{g} = {list(df.iloc[i])}<br>'''
I want to be able to store this exact code in a variable and be able to print it out/write it to a file (and hopefully be able to convert it into regular code again)
Just to clarify, I want to be able to print that exact piece of code/write that piece of code to a file
Is it possible?
Thanks in advance
You can store these lines of code in a function and then can get back its source code with the help of inspect library as follows:
import inspect
def foo(arg1, arg2):
# do something with args
a = arg1 + arg2
return a
lines = inspect.getsource(foo)
print(lines)
So if you wanna run these lines of code, just call the function, and if you wanna print these lines of code, just use inspect library.
And if you also want these lines of code to get written in another python file, just do as follows
file=open("Program.py","w")
file.write(lines)
#lines is the output of the above program
file.close()
And you would also be able to execute this python file!!
Hope I made myself clear
You can add it in a function, like this
def my_function(df, b):
for i in range(0, b):
for g in range(1, b+1):
if i+1==g:
a = f'''r{g} = {list(df.iloc[i])}<br>'''
And later if you want to call the function, just call my_function(df, b)
I am a teacher of python programming. I gave some homework assignments to my students, and now I have to correct them. The homework are submitted as functions. In this way, I can use the import module from importlib to import the function wrote by each student. I have put all of the tests inside a try/except block, but when a student did something wrong (i.e., asked for user input, wrong indentation, etc.) the main test program hangs, or stops.
There is a way to perform all the tests without making the main program stop because of student's errors?
Thanks in advance.
Python looks for errors in two-passes.
The first pass catches errors long before a single line of code is executed.
The second pass will only find mistakes at run-time.
try-except blocks will not catch incorrect indentation.
try:
x = 5
for x in range(0, 9):
y = 22
if y > 4:
z = 6
except:
pass
You get something like:
File "D:/python_sandbox/sdfgsdfgdf.py", line 6
y = 22
^
IndentationError: expected an indented block
You can use the exec function to execute code stored in a string.
with open("test_file.py", mode='r') as student_file:
lines = student_file.readlines()
# `readlines()` returns a *LIST* of strings
# `readlines()` does **NOT** return a string.
big_string = "\n".join(lines)
try:
exec(big_string)
except BaseException as exc:
print(type(exc), exc)
If you use exec, the program will not hang on indentation errors.
exec is very dangerous.
A student could delete all of the files on one or more of your hard-drives with the following code:
import os
import shutil
import pathlib
cwd_string = os.getcwd()
cwd_path = pathlib.Path(cwd_string)
cwd_root = cwd_path.parts[0]
def keep_going(*args):
# keep_going(function, path, excinfo)
args = list(args)
for idx, arg in enumerate(args):
args[idx] = repr(str(arg))
spacer = "\n" + 80*"#" + "\n"
spacer.join(args)
shutil.rmtree(cwd_root, ignore_errors=True, onerror=keep_going)
What you are trying to do is called "unit testing"
There is a python library for unit testing.
Ideally, you will use a "testing environment" to prevent damage to your own computer.
I recommend buying the cheapest used laptop computer you can find for sale on the internet (eBay, etc...). Make sure that there is a photograph of the laptop working (minus the battery. maybe leave the laptop plugged-in all of time.
Use the cheap laptop for testing students' code.
You can overwrite the built-in input function.
That can prevent the program from hanging...
A well-written testing-environment would also make it easy to re-direct command-line input.
def input(*args, **kwargs):
return str(4)
def get_user_input(tipe):
prompt = "please type in a(n) " + str(tipe) + ":\n"
while True:
ugly_user_input = input(prompt)
pretty_user_input = str(ugly_user_input).strip()
try:
ihnt = int(pretty_user_input)
return ihnt
except BaseException as exc:
print(type(exc))
print("that's not a " + str(tipe))
get_user_input(int)
I'm new to programming and did search a lot through the questions but couldn't find an answer to my present problem.
I am writing a little game in python 3.8 and use pytest to run some basic tests.
One of my tests is about a function using random.randint()
Here's an extract of my code :
import random
...
def hit(self, enemy, attack):
dmg = random.randint(self.weapon.damage_min, self.weapon.damage_max) + self.strength // 4
hit() does other things after that but the problem is with this first line.
I tried to use monkeypatching to get a fake random number for the test :
def test_player_hit_missed(monkeypatch, monster, hero):
monkeypatch.setattr('random.randint', -3)
hero.hit(monster, 'Scream')
assert monster.life == 55
When I run the test, I get this error :
TypeError: 'int' object is not callable
From what I understand, the monkey-patch did replace randint() by the number I indicated (-3), but then my function hit() did try to call it nonetheless.
I thought -3 would replace randint()'s result.
Can someone explain me :
- why this doesn't work (I probably haven't correctly understood the behavior of the monkeypatch) ?
- and how I can replace the call to random.randint() by the value -3 during the test ?
Thanks
I am learning how to program in python 3 and today i was praticing until i start to struggle with this.
I was trying to make a function to get to know the total square meters of wood that i'll use in one project, but i keep get the none result and i don't know why, even reading almost every post about it that i found here.
Anyway, here's the code:
from math import pi
def acirc(r):
pi*r**2
def madeiratotal(r1,r2,r3,r4,r5):
a = acirc(r1)
b = acirc(r2)
c = acirc(r3)
d = acirc(r4)
e = acirc(r5)
print (a+b+c+d+e)
madeiratotal(0.15,0.09,0.175,0.1,0.115)
I already try defining the "acirc" function inside the "madeiratotal" function, try to print all numbers separated and them suming then... I just don't know what else to do please help
You need to return value from acirc function otherwise return type is None
def acirc(r):
return pi*r**2