IronPython.Runtime.UnboundNameException: name 'str' is not defined - c#

I'm trying to run an IronPython script in C# but sometimes when I run it I get this error:
IronPython.Runtime.UnboundNameException: name 'str' is not defined
I can't figure out why this is happening; it only happens sometimes; right now it happens when I click a planet in my game to view the report on its abilities.
Here's the script I'm trying to run:
'Mines ' + str(Amount1) + ' minerals each turn (modified by planet value).'
As you can see I'm trying to concatenate some strings, one of which is a stringified Amount1 variable (Amount1 I think is the number 800 but it might be a more complex expression equal to 800, I'd have to check on that), but for some reason I'm getting an error saying the str function is undefined, which makes no sense!
There are other scripts being included before this script runs; if you like I can find those and paste them here in case that might help...
edit: here's the full script that I'm running:
import sys, imp;
import __builtin__ as builtins;
builtins_code = """""";
exec builtins_code in builtins.__dict__;
import clr
clr.AddReference('System.Core')
import System
clr.ImportExtensions(System.Linq)
clr.AddReference('FrEee.Core')
import FrEee
import FrEee.Utility
clr.ImportExtensions(FrEee.Utility.Extensions)
from FrEee.Modding import Mod
from FrEee.Game.Objects.Space import Galaxy
from FrEee.Game.Objects.Civilization import Empire
'Mines ' + str(Amount1) + ' minerals each turn (modified by planet value).'
Could the exec builtins_code line be deleting the str function? If so, how can I make sure that builtins_code gets added to builtins rather than replacing it?
edit2: nope, even if I remove the first four lines, it crashes when I process a turn in a single player game and then click my homeworld!
edit3: if I put the script in a text file and run it as a watch (see below) it runs just fine, even on the breakpoint where it crashes:
FrEee.Modding.ScriptEngine.EvaluateExpression<string>(System.IO.File.ReadAllText("c:/users/edkol/desktop/test.py")), ac

The line:
exec builtins_code in builtins.__dict__
just adds _ to the interactive environment so it repeats the last evaluated variable. Without that line, _ isn't defined. Note that this feature isn't very useful in a script and could be removed. This seems unrelated to your issue.
It looks like the sole interest of IronPython is to be able to interact easily with Microsoft/C# stuff, but it remains "stable" in 2.7 version and it's probably not as bug-free as the official python versions (similar bug was encountered and not solved on reddit, not that it helps, but you know you're not the only one...).
It has to be a bug because you cannot delete a builtin when it's not overridden:
>>> str
<type 'str'>
>>> del str
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'str' is not defined
Now let's be pragmatic: there's no way someone is going to fix that bug in the near future.
So you could try to "restore" the str name by doing:
str = __builtins__.get('str')
I didn't test this, maybe it's not going to work either once you're in this strange state, but there are other workarounds to get hold of "lost" class names, using an instance and __class__ attribute:
>>> "".__class__(34) # "".__class__ is str
'34'
>>> 0 .__class__(1.4) # note the space to help the parser :)
1
The only problem is that is going to look weird in your code. Don't forget to comment!
Anyway, you don't really need str for this, you can workaround your issue by using str.format on a format string (positional):
'Mines {} minerals each turn (modified by planet value).'.format(Amount1)
or by keyword:
'Mines {Amount1} minerals each turn (modified by planet value).'.format(Amount1=Amount1)
That method doesn't involve str built-in. Not saying that you're not going to have other problems, but even when str is available, this is one prefered way to format a string.
Work your way out by avoiding such errors. Fortunately, python exceptions are explicit and can be catched with a nice traceback.

Related

In Unity when I write Debug.Log(" ") it has an error saying that there is a difference between UnityEngine.Log and System.Log. How do I fix this?

It says there is an ambiguous difference between UnityEngine.Log and System.Log and won't print anything. How do I fix it?
I am sorry that people didn't like my question. I am just a new game dev looking for help.
Your simplest solution is just to always type, in that script:
UnityEngine.Debug.Log("yo !!");
In general if it tells you "blah blah .. difference between AAA and BBB ..."
Simply add either AAA. or BBB. in front of the command in question!
(It is usually the "Unity" one you want.)
I wouldn't bother trying to understand it more than that for now, until you are more familiar with it.
It relates to the things you write up the top of the script with "Using...".

Template class names in weird forms (.NET)

I'm retrieving the names of all the classes in the current runtime in .NET, for the purpose of identifying object and function declarations in sourcecode that's given as input to my program, but templates seem a bit off, for example I've got this among the output:
hashset`1+elementcount[t]
hashset`1+slot[t]
hashset`1+enumerator[t]
which I obtain more or less from this simple code (there's some similar code that gets the referenced assemblies but essentially does the following for each of those instead of the executing assembly).
foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
{
types.Add(t.ToString().Split('.').Last().ToLower());
}
For now I can of course just Split() the strings to get the first part, before the ` mark, but I was wondering if anyone knows exactly what this might be. The three lines above are consecutive, and a couple more entries for HashSet in my results also have this 1+something thing, so I'm positive it's the actual HashSet class. (note: I'm turning everything to lowercase currently but disabling it doesn't seem to change anything.)
So... anyone know what's this notation? Not sure how to google it, but copy-pasting some lines to Google and enclosing in quotes returns either no results or very random threads that don't end up having the line in them. Thanks in advance.

Tracking method "bloat" over time with nDepend

We are looking at using nDepend to start tracking some of our technical debt, particularly around hard to maintain methods and cyclomatic complexity.
I believe this is possibly by taking a baseline report and then running a new analysis to provide the delta. Below is a very basic Powershell I've put together that does this.
$nDepend = "C:\_DEVELOPMENT\nDepend\NDepend.Console.exe"
$targetFile = "C:\_DEVELOPMENT\AssemblyToTest\CodeChallenge.Domain.ndproj"
$projectFolder = Split-Path -Path $targetFile
$outputFolder = "nDepend.Reports"
$previous = ""
Clear-Host
# See if we already have a .ndar file in the output folder, if we do back it up so we can do a comparison
if (Test-Path $projectFolder\$outputFolder\*.ndar)
{
Write-Output "Backing up previous NDAR report"
Copy-Item $projectFolder\$outputFolder\*.ndar $projectFolder\previous.ndar
$previous = ".\previous.ndar"
}
#The output path appears to be relative to the .ndproj file
& $nDepend $targetFile /Silent /OutDir .\$outputFolder /AnalysisResultToCompareWith .\previous.ndar
Here is the rule I've configured in nDepend: -
failif count > 1 bobs
from m in Methods
where m.NbLinesOfCode > 10
where m.WasChanged()
select new { m, m.NbLinesOfCode }
The goal of this is not to break the build if we have methods over 10 lines, but rather to break the build if somebody edits an existing method that is too big and does not improve it (or make it worse). However the where m.WasChanged() part of the rule isn't being triggered regardless of how much code I add. If I comment it out it will alert me that there are plenty of methods that exceed 10 lines, but I only want to know about recently changed ones.
Am I using the rule wrong? Or perhaps my powershell is incorrectly using the /AnalysisResultToCompareWith parameter?
There are default rules like Avoid making complex methods even more complex in the rule group Code Smells Regression that are close to what you want to achieve. You can get inspired by their source code.
The key is to retrieve the methods changed with...
m.IsPresentInBothBuilds() &&
m.CodeWasChanged() &&
and then compare metric evolution since baseline by accessing m.OlderVersion().
A ICompareContext reference two code bases snapshots the newer version and the older version. In this context the OlderVersion() extension method returns actually calls the ICompareContext.OlderVersion(codeElement), from the doc:
Returns the older version of the codeElement object.
If codeElement is already the older version, returns the codeElement object.
If codeElement has been added and has no corresponding older version, returns null.
This method has a constant time complexity.

Is there compile-time access to line numbers in C#?

I'm writing a C# program using Visual Studio 2010 where I want to write out certain events to a log file and include the line number the code was on when that happened.
I've only found two ways of capturing line numbers - CallerLineNumber, which requires .Net 4.5/C#5 (I'm targeting .Net 4) and StackFrame.GetFileLineNumber, which apparently requires a debug build and pdb file to work properly, and I'm producing a release build and no pdb file.
But here's what I don't get - both of the above are run-time solutions, but line numbers are compile-time entities. Why is a runtime solution necessary?
I could type in the correct line number as a literal constant by just looking at the bottom of the screen where it says something like "ln 175" . . .
LogEvent("It happened at line 175");
but the problem with that is that if I edit any code before line 175 my literal might no longer be correct. But the compiler knows the correct line number and I've used programming languages in the past that could just pop in the correct line number as a compile time constant. (e.g., ANSI C and Microsoft C++ support a predefined macro called
_LINE_) Is there any way to get C# to do that? If not are there any solutions to my problem?
CAVEATS: This is NOT an answer to the OP. I know that. But people looking for something similar may find this page.
This is not about .NET 4.
This is still ultimately a run-time solution.
But VS 2015, C#, .NET Core or .NET 4.5 allow:
using System.Runtime.CompilerServices;
using System.Diagnostics;
public static String CurrentLocation(
[CallerFilePath] string file = null,
[CallerLineNumber] int lineNumber = 0,
[CallerMemberName] string method = null)
{
String location = file;
if (lineNumber != 0)
{
location += "(" + lineNumber.ToString() + ")";
}
if (!String.IsNullOrWhiteSpace(method))
{
location += ": " + method;
}
if (!String.IsNullOrWhiteSpace(location))
{
location += ": ";
}
return location;
}
[UPDATED USAGE]
With usage something like:
Console.Error.WriteLine(CurrentLocation() + "some message");
or
Debug.WriteLine(CurrentLocation() + "some message");
No, C# doesn't have a macro preprocessor or any meta programming features, so there are no "Compile time" solutions in the entire language. But there are 3rd party macro languages out there that you can use, if you have to, but of course it complicates the build process, Visual Studio won't just figure out how to built it by itself.
You can even use the C preprocessor if you want it. (assuming MSVC compiler)
cl.exe /TC /P /C /EP something.cs > something.raw.cs
cl.exe is the C compiler
/TC tells the C compiler to treat all files as C sources despite their extensions
/P tells the C compiler to only preprocess the file do not compile it
/C preserves the comments
/EP prevents the compiler from generating #line directives, that the C# compiler wouldn't understand
This will allow you to use #include, #define and #if as well as __FILE__ and __LINE__ in your C# program, but again you have to set up Visual Studio to do this additional compilation step, or use a different build system.
One option would be to use the StackTrace class, like so
[Conditional("DEBUG")]
public static void DebugPrintTrace()
{
StackTrace st = new StackTrace(true);
StackFrame sf = st.GetFrame(1);
Console.WriteLine("Trace "
+ sf.GetFileName() + " "
+ sf.GetMethod().Name + ":"
+ sf.GetFileLineNumber() + "\n");
}
In my opinion, line numbers are the wrong approach. Let me explain:
How unique is line number 175? Even if you find a solution, the next question is: which file was it? And it will repeat: if you know the file, you'll ask yourself: which version of the file was it? And you'll integrate the revision number of your source control system. Once you did that, the question will come up: who was calling that code.
If you're debugging an exception, use a debugger and break on first chance exceptions.
If you're analyzing a performance issue, line numbers don't matter, anything unique will do. Try a memory profiler.
If your methods are too long to identify the problems, refactor your code and make the methods shorter. With short methods, you can use an AOP framework like PostSharp with its logging aspect to achieve at least the CallerMemberName feature. It's available down to .NET 2.0 and it's very easy to add logging and remove logging, not like deleting single lines in your code.

Advice for C# programmer writing Python [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I've mainly been doing C# development for the past few years but recently started to do a bit of Python (not Iron Python). But I'm not sure if I've made the mental leap to Python...I kind of feel I'm trying to do things as I would in C#.
Any advice on how I can fully take advantage of Python?
Or any tips\tricks, things to learn more about, things to watch out for?
First, check tgray's and Lundström's advice.
Then, some things you may want to know:
Python is dynamically typed, so unlike C#, you will not
check type, but behavior. You may want to google about duck
typing. It implies you do not have to deal with boxing and
unboxing.
Python is fully object oriented, but the syntax does not
enforce this paradigm. You can write Python without using
the word "class".
The GUI library featured with Python can't compare with
C#'s. Check PyQt, GTK or wxPython libraries.
Python has a lot of concepts you may not be familiar with:
list comprehensions, generators ("yield" does exist in C#,
but it is not used much), decorators, metaclasses, etc. Don't
be afraid; you can program in Python without them. They
are just smart tools, not mandatory.
Like in C#, the Python standard library is huge. Always
look at it when you encounter any problem. It is most
likely that someone solved it already.
Python use LATE binding and variable labels. It's far too
early for somebody starting with the language to worry
about it, but remember that one day you will encounter a
behavior with variables that SEEMS illogical, and you'll
have to check that. For the moment:
Just remember to never do the following:
def myfunc(my_list=[]) :
# bla
Instead:
def myfunc(my_list=()) :
my_list = list(my_list)
And you'll be good. There is a good reason for that, but
that's not the point :-)
Python is cross platform, enjoy writing on Mac, and
run on Linux, if you wish.
Python is not provided with a complex IDE (you got IDLE :-)).
If you are a Visual Studio addict, check Glade. This is
not as advanced as Visual Studio, but it's still a good RAD.
If you want to develop some web application in Python,
remember that Python is not .NET. You must add a web
framework to it if you want to compare. I like Django.
Python does not need a huge IDE to work with. SciTE,
Notepad++, IDLE, Kate, gedit...
Lightweight editors are really sufficient.
Python enforces indentation using spaces and line break,
you can't change that. You should avoid using tabs for
indenting and choose spaces instead. The equivalent of
empty bracelets {} is the keyword "pass".
Python does not enforce private variables. You can define a
private var using "__" (two underscores) at the beginning of
the variable name, but it's still bypassable in some tricky
ways. Python usually assume programmers are grown adults
that know what they do and communicate.
Python uses iteration. A lot. A lot of a lot. And so the
itertools module is you best friend.
Python has no built in delegates. The delegate module is
not what you think. For event-driven programming, use a
GUI lib (or code the pattern yourself, it's not that
difficult).
Python has an interpreter: you can test almost anything,
live. It should always be running next to your text
editor. Python basic interpreter is not much, try IPython
for something tasty.
Python is autodocumented: use docstrings in your own code
and consult other's using "help()" in the python interpreter
Module basics:
sys: manipulate system features
os: set credential, manipulate file paths, rename, recursive file walk, etc
shutil: batch file processing (such as recursive delete)
re: regexp
urllib and urllib2: HTTP¨scripting like downloading, post / get resquests, etc.
datetime: manipulate date, time AND DURATION
thread: you guess it
zlib: compression
pickle: serialization
xml: parsing / Writing XML with SAX or DOM
There are hundreds of modules. Enjoy.
Some typical ways to do things in Python:
Loops:
Python coders use massively the equivalent of the foreach C#
loop, and prefer it to any others:
Basic iterations:
for item in collection:
print str(item)
"collection" can be a string, a list, a tuple... Any
iterable: any object defining the .next() method. There are
a lot of iterables in Python. E.g: a typical Python idiom
to read files:
for line in open("/path/to/file") :
print line
A shortcut to the for loop is called "list comprehension".
It's a way to create an new iterable in one line:
Creating a filtered list with list comprehension:
my_list = [item for item in collection if condition]
Creating a new list with a list comprehension:
my_list = [int(item) * 3 for item in collection]
Creating a new generator with a list comprehension:
my_list = (int(item) * 3 for item in collection)
Same as above, but the values will be generated on the fly
at the first iteration then lost. More information about it here.
Ordinary for loop
If you want to express a usual for loop, you can use the
xrange() function. for (int i = 0; i < 5; i++) becomes:
for i in xrange(0,5) :
do while equivalent
There is no "Do While" in Python. I never missed it, but if
you have to use this logic, do the following:
while True : # Yes, this is an infinite loop. Crazy, hu?
# Do your stuff
if condition :
break
Unpacking
Swapping variables:
a, b = b, a
Multiple assignations:
The above is just a result of what we call "unpacking" (here
applied to a tuple). A simple way to explain it is that you
can assign each value of any sequence directly to an equal
number a variables, in one row:
animal1, animal2, animal3, animal4 = ["cow", "dog", "bird", "fish"]
This has a lot of implications. While iterating on a
multidimensional array, you normally get each sub sequence
one by one then use it, for example:
agenda = [("steve", "jobs"), ("linus", "torvald"), ("bill", "gates"),("jon", "skeet")]
for person in agenda:
print person[0], person[1]
But with unpacking, you can assign the values directly to
variables as well:
agenda = [("steve", "jobs"), ("linus", "torvald"), ("bill", "gates"),("jon", "skeet")]
for name, lastname in agenda:
print name, lastname
And that's why if you want to get an index while iterating,
Python coders use the following idioms (enumerate() is a
standard function):
for index, value in enumerate(sequence) :
print index, value
Unpacking in functions calls
This is advanced use, and you can skip it if it bothers you.
You can unpack values using the sign "*" to use a sequence
directly in a function call. E.g:
>>> foo(var1, var1, var3) :
print var1, var2
print var3
>>> seq = (3.14, 42, "yeah")
>>> foo(*seq)
3.14 42
yeah
There is even more than that. You can unpack a dictionary as
named variables, and write function prototypes with *,
** to accept an arbitrary number of arguments. But it not
used enough to deserve to make this post even longer :-).
String formatting:
print "This is a %s on %s about %s" % ("post", "stackoverflow", "python")
print "This is a %(subject)s on %(place)s about %(about)s" % {"subject" : "post", "place" : "stackoverflow", "about" : "python"}
Slicing an iterable:
You can get any part of an iterable using a very concise syntax:
print "blebla"[2:4] # Print "eb"
last = string[:-1] # Getting last element
even = (0,1,2,3,4,5,6,7,8,9)[::2] # Getting evens only (third argument is a step)
reversed = string[::-1] # Reversing a string
Logical checks:
You can check the way you do in C#, but there are "Pythonic"
ways (shorter, clearer :-)):
if 1 in (1, 2, 3, 4) : # Check en element is in a sequence
if var : # check is var is true. Var == false if it's False, 0, (), [], {} or None
if not var : # Contrary of above
if thing is var: # Check if "thing" and "var" label the same content.
if thing is None : # We use that one because None means nothing in Python (almost null)
Combo (print on one line all the words containing an "o" in uppercase ):
sentence = "It's a good day to write some code"
print " ".join([word.upper() for word in sentence.split() if "o" in word])
Output: "GOOD TO SOME CODE"
Easier to ask for forgiveness than permission
Python coders usually don't check if something is possible. They are a bit like Chuck Norris. They do it. Then catch the exception. Typically, you don't check if a file exists, you try to open it, and roll back if it fails:
try :
f = open(file)
except IOerror :
print "no file here !"
Of course Chuck Norris never uses excepts since he never fails.
The else clause
"Else" is a world of many uses in Python. You will find
"else" after "if", but after "except" and "for" as well.
for stuff in bunch :
# Do things
else :
# This always happens unless you hit "break" in the loop
This works for "while" loop too, even if we do not use this
loop as much.
try :
# A crazy stuff
except ToCrazyError :
# This happens if the crazy stuff raises a ToCrazyError Exception
else :
# This will happen if there is no error so you can put only one line after the "try" clause
finally :
# The same as in C#
If you are curious, here is a bunch of advanced quick and
dirty (but nice) Python snippets.
Refrain from using classes. Use dictionaries, sets, list and tuples.
Setters and getters are forbidden.
Don't have exception handlers unless you really need to - let it crash in style.
Pylint can be your friend for more pythonish coding style.
When you're ready - check out list comprehensions, generators and lambda functions.
If you are not new to programming, I would recommend the book "Dive into Python" by Mark Pilgrim. It explains Python in a way that makes it easy to understand how Python techniques and idioms can be applied to build practical applications.
Start by reading The Zen of Python
You can read it at the link above, or just type import this at the Python prompt. =)
Take advantage of Python features not offered* by C#
Such as duck-typing, metaclasses, list comprehension, etc.*
Write simple programs just to test these features. You'll get used (if not addicted) to them in no time.
Look at the Python Standard Library
So you don't reinvent the wheel. Don't try to read the whole thing, even a quick look at the TOC could save you a lot of time.
* I know C# already has some of these features, but from what I can see they're either pretty new or not commonly used by C# developers. Please correct me if I'm wrong.
In case you haven't heard about it yet, Dive Into Python is a great place to start for anyone learning Python. It also has a bunch of Tips & Tricks.
If you are someone who is better learning a new language by taking small incremental steps then I would recommend using IronPython. Otherwise use regular CPython and don't do any more C# coding until you feel like you have a grasp of Python.
I would suggest getting a good editor so that you don't get bitten by whitespace. For simplicity, I just use ActivePython's packages Link, which include an editor and all of the win32api libraries. They are pretty fun to get into if you have been using C#. The win32api in Python can be a little bit simpler. You don't need to do the whole DDLImport thing. Download ActivePython (which comes with CPython), open it up, and start entering some stuff at the console. You will pick it up fairly easy after using C#. For some more interesting Python tidbits, try ActiveState code, which has all sorts of recipes, which can allow you to very simply see different things that you can do with Python.
I'm pretty much in your shoes too, still using C# for most of my work, but using Python more and more for other projects.
#e-satis probably knows Python inside-out and all his advice is top-notch. From my point of view what made the biggest difference to me was the following:
Get back into functional. not necessarily spaghetti code, but learning that not everything has to be in an object, nor should it be.
The interpreter. It's like the immediate window except 10^10 better. Because of how Python works you don't need all the baggage and crap C# makes you put in before you can run things; you can just whack in a few lines and see how things work.
I've normally got an IDLE instance up where I just throw around snippets as I'm working out how the various bits in the language works while I'm editing my files... e.g. busy working out how to do a map call on a list, but I'm not 100% on the lambda I should use... whack in a few lines into IDLE, see how it works and what it does.
And finally, loving into the verbosity of Python, and I don't mean that in the long winded meaning of verbosity, but as e-satis pointed out, using verbs like "in", "is", "for", etc.
If you did a lot of reflection work in C# you'll feel like crying when you see how simple the same stuff is in Python.
Good luck with it.
If you have programming experience and don't feel like spending money I'd recommend How to Think Like a Computer Scientist in Python.
And then something you can benefit from:
IPython shell: Auto completion in the shell. It does batch operations, adds a ton of features, logging and such. >>> Play with the shell - always!
easy_install / pip: So nice and an easy way to install a 3rd party Python application.

Categories

Resources