Python Interface: Extract strings from seqquence

Here's the place for discussion related to coding in FreeCAD, C++ or Python. Design, interfaces and structures.
Forum rules
Be nice to others! Respect the FreeCAD code of conduct!
Post Reply
ickby
Veteran
Posts: 3116
Joined: Wed Oct 05, 2011 7:36 am

Python Interface: Extract strings from seqquence

Post by ickby »

Hello,

I'm struggling with the Python c-api again... I try to extract strings, either directly passed or as partof a sequence. If the sting is always directly passed one could use PyArgs_ParseTuple, which works fine. This way I get the correct string. But I struggle to extract it from a sequence. Here is my code, and the string I retrieve is always "1" Does anyone have a idea how to extract string from a sequence?

Code: Select all

        auto handleItem = [&](PyObject* item) {
            if (PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) {
                auto shape = static_cast<Part::TopoShapePy*>(item)->getTopoShapePtr();
                //handle shape
            }
            else if (PyObject_TypeCheck(item, &PyBaseString_Type)) {
                const char* _hash = PyString_AsString(item);
                std::string hash(_hash);
                //handle string             
            }
            else {
                PyErr_SetString(PyExc_TypeError, "wrong types");
                return 0;
            }
        };
            
        if(PySequence_Check(_base)) {
            Py::Sequence list(_base);
            for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) {
                PyObject* item = (*it).ptr();
                handleItem(item);
            }
        }
        else 
            handleItem(_base);
 
wmayer
Founder
Posts: 20319
Joined: Thu Feb 19, 2009 10:32 am
Contact:

Re: Python Interface: Extract strings from seqquence

Post by wmayer »

Be careful: a Python string itself is a sequence. So, if you want to support a single string and a sequence of strings you must first explicitly check for the string (and if needed unicode) type and otherwise use sequence protocol (e.g. in form of Py::Sequence)
Post Reply