How to pass a string of keyword arguments into a function

How to pass a string of keyword arguments into a function

Having encountered, the seemingly impossible in Python, difficulty of passing a string of keyword arguments into a function like this:

args_in = "arg1 = 'var1', arg2 = 2, arg3 = True, arg4='var4'"

def myFunc(arg1=None, arg2=None, arg3=None, arg4=None):
    print(f"{arg1=}, {arg2=}, {arg3=}, {arg4=}")

myFunc(args_in)

One solutions I found was to use eval():

eval("myFunc(" + args_in ")") 

although I am informed that this is the work of the devil and should be avoided at all costs.

Next attempts were to convert the "string" into a dict{} and pass **dict, however all methods for doing this failed when any of the arguments contained a comma ','.

However a fully working solution to this was finally provided to me on the discuss.python.org forum:

args_in = "arg1 = 'var1', arg2 = 2, arg3 = True, arg4='va,r4'"

def myFunc(arg1=None, arg2=None, arg3=None, arg4=None):
    print(f"{arg1=}, {arg2=}, {arg3=}, {arg4=}")

def str2dict(str_in: str) -> dict[str, str]:
    import ast
    return {pair.arg: ast.literal_eval(pair.value)
        for pair in ast.parse(f"f({str_in})").body[0].value.keywords}

myFunc(**str2dict(args_in))

Unfortunately due to rather rude and overly zealous moderation on there that solution was deleted. Hence the reason for publishing it here for the archive and in case it helps someone else in the future.

u/RomfordNavy — 14 days ago

Subclass mysql.connector

Any idea what I am doing wrong when trying to subclass mysql.connector like this:

import mysql.connector

class Database(mysql.connector.MySQLConnection):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

db = Database()
print(db) # <- returns None

db_conn = db.connect(host = '...', database = '...', user = '...', passwd = '...')

db always returns None.

reddit.com
u/RomfordNavy — 23 days ago
▲ 4 r/Python

Checking whether a mysql.connector is connected

Is it necessary to check whether a mysql.connector is connected each time I reuse it before running any SQL statements or is this something which is already built-in to mysql.connector? Do I need to check for connection using db.is_connected() and write some retry routine.

This is a WSGI webserver, could be wrong, but my understanding is that there can only ever be one request/thread at a time. Connection pooling has been suggested elsewhere but I am unclear as to whether that is necessary and/or appropriate for a WSGI webserver.

reddit.com
u/RomfordNavy — 23 days ago

Balanced cable for Arya Organic

Can anyone suggest a good balanced cable for my Arya Organics which ends in either an XLR-4 or 4.4mm for connecting them to a Douk Audio U5 Pro. Preferably something which is not too heavy and doesn't feel like wearing a chain. On the other hand I don't want anything too thin which looses the beautifully warm vocals.

reddit.com
u/RomfordNavy — 23 days ago

Alternative to SL-M610 I-spec-B with display window

Anyone know if there is an alternative to SL-M610 I-spec-B shifter but with a display window. This mounts directly onto the BL-M506 brake lever but I am not sure if with those brake levers there is enough room to mount a band-on unit.

reddit.com
u/RomfordNavy — 1 month ago

Alternative to SL-M610 I-spec-B with display window

Anyone know if there is an alternative to SL-M610 I-spec-B shifter but with a display window. This mounts directly onto the BL-M506 brake lever but I am not sure if with those brake levers there is enough room to mount a band-on unit.

reddit.com
u/RomfordNavy — 1 month ago

Titanium pans

Have tried a tin-lined hammered copper pan but that didn't have quite the non-stick properties that I had expected, seem to be constantly soaking it out with bicarb to clean it rather than just wiping it out.

I keep seeing all these adverts for various Titanium pans and can't help but wonder if these are anywhere near as good as claimed. Is anyone using one on a daily basis in a commercial environment?

reddit.com
u/RomfordNavy — 2 months ago

Front fork oil

Can I use motorcycle fork oil in my RockShox Revelation forks?

Technical spec states that it should be 5wt, will this stuff from eBay be correct?

u/RomfordNavy — 2 months ago
▲ 0 r/Python

Other Python forums - Stack Overflow

Not sure if I am allowed to discuss other forums on here but I'm sure someone will tell me if not.

It is just me of has anybody else encountered problems with the 'moderators' on Stack Overflow Python forums recently? To say I've found them to be a self-righteous bunch of destructive power-crazy control-freaks would be a bit of an understatement. Anyone else had problems on there?

reddit.com
u/RomfordNavy — 2 months ago

Turn off print() output

Is there some way to switch off print() output when Python is not running in interactive mode?

When I am testing it is good to see these messages on screen but when the process is running without an interactive terminal to output to it feels like it would be good to find a way to stop that output. However I don't know whether the overhead of these messages going nowhere matters or not.

reddit.com
u/RomfordNavy — 4 months ago

Thoughts on HTML / Python template delimiters

Working on creating a small templating type engine to allow mixing of HTML and Python code and considering what to use as the delimiters between each. Beginning suggestion is:

HTML: <- begin HTML block

&lt;% Python expression %&gt;

Python: <- begin Python code block

&lt;# HTML text #&gt;     &lt;- output HTML with newline
&lt;#= HTML text #&gt;    &lt;- output HTML inline (no newline)
? "HTML text"       &lt;- output HTML whole line
?? "HTML text"      &lt;- output HTML whole line (on same line)

Are there more suitable 'Pythonic' delimiters which I should be using?

reddit.com
u/RomfordNavy — 5 months ago

Local variables changed during exec() in Python 3.14 are not persistant

There seems to be a problem with changing a local variable within exec():

test = "test1"
exec("test = 'test2'", {}, {"test": test})
print(test) # &lt;- erroneously returns test1

returns 'test1' - the change to 'test' during exec() has not persisted

However if passed inside a dict variable:

localDict = {"test": "test1"}
exec("test = 'test2'", {}, localDict)
test = localDict["test"]
print(test) # &lt;- correctly returns test2

It seems to work for some reason and returns 'test2'!

Is this a bug in exec() in Python 3.14?

reddit.com
u/RomfordNavy — 5 months ago

Accessing source code from importlib module

I notice that the source code from an importlib module can be read using inspect module. However is there an alternative way of accessing this code so that it can be modified? Presumably inspect.getsource must have some method of finding this.

import inspect
import importlib
spec = importlib.util.spec_from_file_location(module_name, source_path)
module = importlib.util.module_from_spec(spec)
print(inspect.getsource(module))
reddit.com
u/RomfordNavy — 5 months ago

Compile only if .pyc is out-of-date?

Is there some way I can compile a .py script into a .pyc but only if it is missing or out-of-date with the.py file?

I am trying to compile the file if necessary and then run it from within Python, can exec() run a .pyc file?

import py_compile
py_compile.compile('Child.py')
exec(open('Child.py').read())

This works but recompiles the file on every run.

reddit.com
u/RomfordNavy — 5 months ago

How to call a *.py from within Python along with a variable?

What is the correct way to call a *.py program script from within Python while making a variable from the parent available.

Parent.py

class cParent:
    test = "test"
oParent = cParent()
import Child

Child.py

print(oParent.test)     # this line fails presumably because oParent is out of scope
reddit.com
u/RomfordNavy — 5 months ago

Create .pyc files for simple scripts

It it possible to configure Python to create a .pyc bytecode file for all simple *.py files which are run? It seems that by default it only creates a .pyc for any classes which is imported not for a program file itself.

reddit.com
u/RomfordNavy — 5 months ago

Well, had a good listening session today and here are my thoughts:

  • Fiio FT7 - quite clinical, vocals sounded 'dry'
  • Meze 105 - much warmer midrange but maybe lacked the spacial seperation and overall range of the Fiio, also very tight clamping force
  • Audeze MM-100 - similar to the Meze, lacking the detail and overall range of the Fiio
  • Hifiman Arya Organic - beautiful vocals but big hole in the treble (2khz?)
  • Hifiman HE1000 Stealth - Hifiman have fixed the hole in the treble here but the result is just way too bright, they make even the FT7 sound warm and not so analytical
  • Dan Clark Noire XO - seemed to lack punch and dynamism, not as impressed as I thought I would be with them
reddit.com
u/RomfordNavy — 5 months ago

Somewhere recently I saw an example of what was probably a WSGI server which had code to run the *.py file which had been requested, however can't seem to find that again. Lots of examples of simple WSGI servers but not the example I was looking for, anyone know where I might find that example?

reddit.com
u/RomfordNavy — 5 months ago

Coming from the Foxpro world we used Textmerge to output multiline text such as HTML, is there a similar method available in Python?

In Fox an example might be:

Use Customer
Set Textmerge On
\&lt;html&gt;
\&lt;head&gt;
\&lt;title&gt;HTML from FoxPro&lt;/title&gt;
\&lt;/head&gt;
\&lt;body&gt;
\&lt;h1&gt;Customer List&lt;/h1&gt;
\&lt;hr /&gt;
Scan
   \Company name is &lt;&lt;Upper(Company)&gt;&gt;
   \&lt;br /&gt;
Endscan
\&lt;/body&gt;
\&lt;/html&gt;
Set Textmerge Off
Use In Customer

reddit.com
u/RomfordNavy — 6 months ago

Can anyone tell me how to use Python to return a simple HTML page using something akin to the ASP Request/Response objects please?

There are lots of examples using various frameworks but can't find anything showing how to just do something very basic.

reddit.com
u/RomfordNavy — 6 months ago