Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C#
* D lang.
* Java
* Nim
* Nim2
  + exercises
* XC=BASIC
* old
  ◇C++, ◇Clojure, ◇Scala


[ edit | logout ]
[ sandbox | passwd ]

From Nim, call Python's eval() function

This is a powerful stuff. For Python's eval() —in the form of a string— you can pass any expression and the Python interpreter will evaluate it and return the value of the expression:

print(eval("1 + 1"))         # 2

print(eval("2 ** 3 - 1"))    # 7

Note: eval() can be a dangerous function! Don't eval a string that comes from an untrusted source! If you eval a malicious string, very bad things can happen!

Problem

I couldn't call eval() directly from a Nim program. I got an error message that globals and locals must be passed to eval(). It may be an issue of nimpy, I found a ticket about it here. However, there's a workaround.

Solution

There's a solution for the previous problem: create a Python module with a function that calls eval() for you.

$ tree .
.
├── helper.py
└── main.nim

helper.py :

def myeval(code):
    return eval(code)

main.nim :

import std/os

import pkg/nimpy

proc main() =
  let sys = pyImport("sys")
  discard sys.path.insert(0, getAppDir())  # directory of the running binary

  let
    helper = pyImport("helper")
    result = helper.myeval("2 ** 3 - 1").to(int)

  echo result             # 7
  echo result.typeOf      # int

main()
Feel the power!
Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 April 24, 17:31