Most Pythonic way to provide global configuration variables in config.py? [closed] - global-variables

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
In my endless quest in over-complicating simple stuff, I am researching the most 'Pythonic' way to provide global configuration variables inside the typical 'config.py' found in Python egg packages.
The traditional way (aah, good ol' #define!) is as follows:
MYSQL_PORT = 3306
MYSQL_DATABASE = 'mydb'
MYSQL_DATABASE_TABLES = ['tb_users', 'tb_groups']
Therefore global variables are imported in one of the following ways:
from config import *
dbname = MYSQL_DATABASE
for table in MYSQL_DATABASE_TABLES:
print table
or:
import config
dbname = config.MYSQL_DATABASE
assert(isinstance(config.MYSQL_PORT, int))
It makes sense, but sometimes can be a little messy, especially when you're trying to remember the names of certain variables. Besides, providing a 'configuration' object, with variables as attributes, might be more flexible. So, taking a lead from bpython config.py file, I came up with:
class Struct(object):
def __init__(self, *args):
self.__header__ = str(args[0]) if args else None
def __repr__(self):
if self.__header__ is None:
return super(Struct, self).__repr__()
return self.__header__
def next(self):
""" Fake iteration functionality.
"""
raise StopIteration
def __iter__(self):
""" Fake iteration functionality.
We skip magic attribues and Structs, and return the rest.
"""
ks = self.__dict__.keys()
for k in ks:
if not k.startswith('__') and not isinstance(k, Struct):
yield getattr(self, k)
def __len__(self):
""" Don't count magic attributes or Structs.
"""
ks = self.__dict__.keys()
return len([k for k in ks if not k.startswith('__')\
and not isinstance(k, Struct)])
and a 'config.py' that imports the class and reads as follows:
from _config import Struct as Section
mysql = Section("MySQL specific configuration")
mysql.user = 'root'
mysql.pass = 'secret'
mysql.host = 'localhost'
mysql.port = 3306
mysql.database = 'mydb'
mysql.tables = Section("Tables for 'mydb'")
mysql.tables.users = 'tb_users'
mysql.tables.groups = 'tb_groups'
and is used in this way:
from sqlalchemy import MetaData, Table
import config as CONFIG
assert(isinstance(CONFIG.mysql.port, int))
mdata = MetaData(
"mysql://%s:%s#%s:%d/%s" % (
CONFIG.mysql.user,
CONFIG.mysql.pass,
CONFIG.mysql.host,
CONFIG.mysql.port,
CONFIG.mysql.database,
)
)
tables = []
for name in CONFIG.mysql.tables:
tables.append(Table(name, mdata, autoload=True))
Which seems a more readable, expressive and flexible way of storing and fetching global variables inside a package.
Lamest idea ever? What is the best practice for coping with these situations? What is your way of storing and fetching global names and variables inside your package?

How about just using the built-in types like this:
config = {
"mysql": {
"user": "root",
"pass": "secret",
"tables": {
"users": "tb_users"
}
# etc
}
}
You'd access the values as follows:
config["mysql"]["tables"]["users"]
If you are willing to sacrifice the potential to compute expressions inside your config tree, you could use YAML and end up with a more readable config file like this:
mysql:
- user: root
- pass: secret
- tables:
- users: tb_users
and use a library like PyYAML to conventiently parse and access the config file

I like this solution for small applications:
class App:
__conf = {
"username": "",
"password": "",
"MYSQL_PORT": 3306,
"MYSQL_DATABASE": 'mydb',
"MYSQL_DATABASE_TABLES": ['tb_users', 'tb_groups']
}
__setters = ["username", "password"]
#staticmethod
def config(name):
return App.__conf[name]
#staticmethod
def set(name, value):
if name in App.__setters:
App.__conf[name] = value
else:
raise NameError("Name not accepted in set() method")
And then usage is:
if __name__ == "__main__":
# from config import App
App.config("MYSQL_PORT") # return 3306
App.set("username", "hi") # set new username value
App.config("username") # return "hi"
App.set("MYSQL_PORT", "abc") # this raises NameError
.. you should like it because:
uses class variables (no object to pass around/ no singleton required),
uses encapsulated built-in types and looks like (is) a method call on App,
has control over individual config immutability, mutable globals are the worst kind of globals.
promotes conventional and well named access / readability in your source code
is a simple class but enforces structured access, an alternative is to use #property, but that requires more variable handling code per item and is object-based.
requires minimal changes to add new config items and set its mutability.
--Edit--:
For large applications, storing values in a YAML (i.e. properties) file and reading that in as immutable data is a better approach (i.e. blubb/ohaal's answer).
For small applications, this solution above is simpler.

How about using classes?
# config.py
class MYSQL:
PORT = 3306
DATABASE = 'mydb'
DATABASE_TABLES = ['tb_users', 'tb_groups']
# main.py
from config import MYSQL
print(MYSQL.PORT) # 3306

Let's be honest, we should probably consider using a Python Software Foundation maintained library:
https://docs.python.org/3/library/configparser.html
Config example: (ini format, but JSON available)
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
Code example:
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.read('example.ini')
>>> config['DEFAULT']['Compression']
'yes'
>>> config['DEFAULT'].getboolean('MyCompression', fallback=True) # get_or_else
Making it globally-accessible:
import configpaser
class App:
__conf = None
#staticmethod
def config():
if App.__conf is None: # Read only once, lazy.
App.__conf = configparser.ConfigParser()
App.__conf.read('example.ini')
return App.__conf
if __name__ == '__main__':
App.config()['DEFAULT']['MYSQL_PORT']
# or, better:
App.config().get(section='DEFAULT', option='MYSQL_PORT', fallback=3306)
....
Downsides:
Uncontrolled global mutable state.

A small variation on Husky's idea that I use. Make a file called 'globals' (or whatever you like) and then define multiple classes in it, as such:
#globals.py
class dbinfo : # for database globals
username = 'abcd'
password = 'xyz'
class runtime :
debug = False
output = 'stdio'
Then, if you have two code files c1.py and c2.py, both can have at the top
import globals as gl
Now all code can access and set values, as such:
gl.runtime.debug = False
print(gl.dbinfo.username)
People forget classes exist, even if no object is ever instantiated that is a member of that class. And variables in a class that aren't preceded by 'self.' are shared across all instances of the class, even if there are none. Once 'debug' is changed by any code, all other code sees the change.
By importing it as gl, you can have multiple such files and variables that lets you access and set values across code files, functions, etc., but with no danger of namespace collision.
This lacks some of the clever error checking of other approaches, but is simple and easy to follow.

Similar to blubb's answer. I suggest building them with lambda functions to reduce code. Like this:
User = lambda passwd, hair, name: {'password':passwd, 'hair':hair, 'name':name}
#Col Username Password Hair Color Real Name
config = {'st3v3' : User('password', 'blonde', 'Steve Booker'),
'blubb' : User('12345678', 'black', 'Bubb Ohaal'),
'suprM' : User('kryptonite', 'black', 'Clark Kent'),
#...
}
#...
config['st3v3']['password'] #> password
config['blubb']['hair'] #> black
This does smell like you may want to make a class, though.
Or, as MarkM noted, you could use namedtuple
from collections import namedtuple
#...
User = namedtuple('User', ['password', 'hair', 'name']}
#Col Username Password Hair Color Real Name
config = {'st3v3' : User('password', 'blonde', 'Steve Booker'),
'blubb' : User('12345678', 'black', 'Bubb Ohaal'),
'suprM' : User('kryptonite', 'black', 'Clark Kent'),
#...
}
#...
config['st3v3'].password #> passwd
config['blubb'].hair #> black

I did that once. Ultimately I found my simplified basicconfig.py adequate for my needs. You can pass in a namespace with other objects for it to reference if you need to. You can also pass in additional defaults from your code. It also maps attribute and mapping style syntax to the same configuration object.

please check out the IPython configuration system, implemented via traitlets for the type enforcement you are doing manually.
Cut and pasted here to comply with SO guidelines for not just dropping links as the content of links changes over time.
traitlets documentation
Here are the main requirements we wanted our configuration system to have:
Support for hierarchical configuration information.
Full integration with command line option parsers. Often, you want to read a configuration file, but then override some of the values with command line options. Our configuration system automates this process and allows each command line option to be linked to a particular attribute in the configuration hierarchy that it will override.
Configuration files that are themselves valid Python code. This accomplishes many things. First, it becomes possible to put logic in your configuration files that sets attributes based on your operating system, network setup, Python version, etc. Second, Python has a super simple syntax for accessing hierarchical data structures, namely regular attribute access (Foo.Bar.Bam.name). Third, using Python makes it easy for users to import configuration attributes from one configuration file to another.
Fourth, even though Python is dynamically typed, it does have types that can be checked at runtime. Thus, a 1 in a config file is the integer ‘1’, while a '1' is a string.
A fully automated method for getting the configuration information to the classes that need it at runtime. Writing code that walks a configuration hierarchy to extract a particular attribute is painful. When you have complex configuration information with hundreds of attributes, this makes you want to cry.
Type checking and validation that doesn’t require the entire configuration hierarchy to be specified statically before runtime. Python is a very dynamic language and you don’t always know everything that needs to be configured when a program starts.
To acheive this they basically define 3 object classes and their relations to each other:
1) Configuration - basically a ChainMap / basic dict with some enhancements for merging.
2) Configurable - base class to subclass all things you'd wish to configure.
3) Application - object that is instantiated to perform a specific application function, or your main application for single purpose software.
In their words:
Application: Application
An application is a process that does a specific job. The most obvious application is the ipython command line program. Each application reads one or more configuration files and a single set of command line options and then produces a master configuration object for the application. This configuration object is then passed to the configurable objects that the application creates. These configurable objects implement the actual logic of the application and know how to configure themselves given the configuration object.
Applications always have a log attribute that is a configured Logger. This allows centralized logging configuration per-application.
Configurable: Configurable
A configurable is a regular Python class that serves as a base class for all main classes in an application. The Configurable base class is lightweight and only does one things.
This Configurable is a subclass of HasTraits that knows how to configure itself. Class level traits with the metadata config=True become values that can be configured from the command line and configuration files.
Developers create Configurable subclasses that implement all of the logic in the application. Each of these subclasses has its own configuration information that controls how instances are created.

Related

How to allow the user to override a subset of the configuration using their own yaml file?

Let's say I have this basic app:
from dataclasses import dataclass
import hydra
from hydra.core.config_store import ConfigStore
#dataclass
class MyAppConfig:
req_int: int
opt_str: str = "Default String"
opt_float: float = 3.14
cs = ConfigStore.instance()
# Registering the Config class with the name 'config'.
cs.store(name="base_config", node=MyAppConfig)
#hydra.main(version_base=None, config_name="base_config", config_path="conf")
def my_app(cfg: MyAppConfig) -> None:
print(cfg)
if __name__ == "__main__":
my_app()
Is it possible for the user to be able to call my app like this:
python my_app.py req_int=42 --config="~/path/to/user-defined-config.yaml"
And user-defined-config.yaml would contain only this:
opt_str: User Config String
The output should look like this:
{'req_int': 42, 'opt_str': 'User Config String', 'opt_float': 3.14, 'config': 'hydra-user-conf'}
The closest I got to that is:
user-defined-config.yaml
defaults:
- base_config
- _self_
opt_str: User Config String
And the invocation:
python hydra/app.py req_int=42 --config-path='~/path/to' --config-name="hydra-user-conf"
But this way the user (who I don't want to require to be familiar with hydra) has to specify the path to their config file via two cli arguments and also include the defaults section in their config, which would be redundant boilerplate to them if they have to always include it in all of their configuration files.
Is this the closest I can get with hydra to the desired interface?
One thing you can do is to pre-configure the config searchpath in the primary config. Adding something like ~/.my_app/ to your config searchpath (thus potentially eliminating the need for --config-path|-cp.
In yaml it would look like:
hydra:
searchpath:
- file://${oc.env:HOME}/.my_app
Another thing to consider is having the app generating an initial config for the user on demand. I took this approach with Configen.
In general, the current patterns are not amazing and maybe there is room for some improvements in Hydra to make this more ergonomic (You can open a discussion about it).

How to add properties with a specific type into gremlinpython?

Currently i am trying to import via gremlinpython a large graph from igraph programmatically . I am rather new to gremlin and the endpoints i may use it with. The problem i currently face is that a property in a node/edge can have multiple types. (E.g.: -> Bool or None-type | Int, Long, etc..)
I've noticed no error when importing it into this gremlin-server (is this called Apache TinkerGraph-Server? How should i call this?). It seems that the types of same properties can be arbitrary.
However, when using JanusGraph i receive multiple errors:
gremlin_python.driver.protocol.GremlinServerError: 500: Value [XXX] is not an instance of the expected data type for property key [YYY] and cannot be converted. Expected: class <SomeClass>, found: class <SomeOtherClass>
E.g. executing:
conn = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
remote_graph = traversal().withRemote(conn)
remote_graph.addV().property("test", 10000).next()
remote_graph.addV().property("test", 100000000000000000000000).next() # <- Causes an error on JanusGraph
It is possible for me to cast some properties into other datatypes (Bool/None-Type-> -1,0,1), so i can avoid this error. But i am not sure how i should handle the above provided example. Is there a way to explicitly set the type (for at least numeric types) of a property, so that the server knows to store it e.g. as a Long/BigInt instead of as a Int? Especially since in python3 there is no distincion between long(/bigint) and int anymore.
So specifically is there something like the following?:
E.g. executing:
remote_graph.addV().property("test", 10000).asLong().next()
remote_graph.addV().property("test", 10000, <Type: Long>).next()
Gremlin does have a special class for ensuring a Java Long. You can just do long(10000) given the appropriate import like: from gremlin_python.statics import long

Sqlalchemy sqlite url relative to home or environment variable

A relative sqlalchemy path to a sqlite database can be written as:
sqlite:///folder/db_file.db
And an absolute one as:
sqlite:////home/user/folder/db_file.db
Is it possible to write a path relative to home? Like this:
sqlite:///~/folder/db_file.db
Or even better, can the path contain environment variables?
sqlite:////${MY_FOLDER}/db_file.db
This is the context of an alembic.ini file. So if the previous objectives are not possible directly, may I be able to cheat using variable substitution?
[alembic]
script_location = db_versions
sqlalchemy.url = sqlite:///%(MY_FOLDER)s.db
...
I have gone around this issue by modifying the values in the config object just after env.py imports it:
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# import my custom configuration
from my_app import MY_DB_URI
# overwrite the desired value
config.set_main_option("sqlalchemy.url", MY_DB_URI)
Now config.get_main_option("sqlalchemy.url") returns the MY_DB_URI you wanted.
As others have pointed out, one key is 3 slashes for relative, 4 for absolute.
But it took for me than just that...
Had trouble with just a string, I had to do this:
db_dir = "../../database/db.sqlite"
print(f'os.path.abspath(db_dir): {str(os.path.abspath(db_dir))}')
SQLALCHEMY_DATABASE_URI = "sqlite:///" + os.path.abspath(db_dir) # works
# SQLALCHEMY_DATABASE_URI = "sqlite:///" + db_dir # fails
From the alembic documentation (emphasis mine):
sqlalchemy.url - A URL to connect to the database via SQLAlchemy. This configuration value is only used if the env.py file calls upon them; in the “generic” template, the call to config.get_main_option("sqlalchemy.url") in the run_migrations_offline() function and the call to engine_from_config(prefix="sqlalchemy.") in the run_migrations_online() function are where this key is referenced. If the SQLAlchemy URL should come from some other source, such as from environment variables or a global registry, or if the migration environment makes use of multiple database URLs, the developer is encouraged to alter the env.py file to use whatever methods are appropriate in order to acquire the database URL or URLs.
So for this case, the sqlalchemy url format can be circunvented and generated by python itself.

Kotlin classes cannot be found when reflecting filepaths to source directories or jars

===Update: Using org.reflections:reflections:0.9.11
Looking to use the following line to pull a list of class names from Kotlin source...
Reflections.getSubTypesOf(Any::class.java)
However I receive a message that Kotlin class files aren't being seen when I run the following script...
val classLoader = URLClassLoader(this.getDirectoryUrls(), null)
println("retrieved class loader")
val config = getConfig(classLoader)
println("retrieved source config")
val reflections = Reflections(config)
println("retrieved reflections")
// For 3 paths: Reflections took 3 ms to scan 3 urls, producing 0 keys and 0 values
=== Update: The 3 urls added by "getDirectoryUrls()" are directories containing kotlin class source files.
Below is my config... ideas?
private fun getConfig(classLoader: ClassLoader): ConfigurationBuilder {
val config = ConfigurationBuilder().setUrls(ClasspathHelper.forClassLoader(classLoader))
// .setScanners(SubTypesScanner(false), ResourcesScanner())
if (!packagePath.isNullOrBlank()){
System.out.println("looking in package [$packagePath]")
config.filterInputsBy(FilterBuilder().include(FilterBuilder.prefix(packagePath)))
}
config.addClassLoader(classLoader)
config.setScanners(SubTypesScanner(), TypeAnnotationsScanner())
return config
}
Setting SubTypesScanner(false) seems to be required to get any types with getSubTypesOf(Any::class.java) (that parameter itself stands for excludeObjectClass). Looking at the bytecode of Kotlin classes you immediately see, that they are actually looking the same as Java classes. There is no Any-superclass there. Note that Kotlins Any is actually also in other means very similar to Javas Object (but not the same, check also the following answer to 'does Any == Object'). So, we need to include the Object-class when scanning for subtypes of Any (i.e. excludeObjectClass=false).
Another problem could be the setup of your URL array. I just used the following to setup the reflections util:
val reflections = Reflections(ConfigurationBuilder()
.addUrls(ClasspathHelper.forPackage("my.test.package"))
.setScanners(TypeAnnotationsScanner(), SubTypesScanner(false)))
which will resolve all matching subtypes and will return subtypes also for Any.
reflections.getSubTypesOf(MyCustomSuperType::class.java).forEach(::println)
reflections.getSubTypesOf(Any::class.java).forEach(::println)
Analysing further: you mention "Kotlin class source files"... if that means you are pointing to the directory containing the .kt-files, then that is probably your problem. Try to use the directory which contains the .class-files instead. Moreover, ensure that the classes are on the classpath.
Maybe you know already, maybe not? Note also that if you have a (classes) directory, say /sample/directory, which is on the classpath and which contains a package, say org.example (which corresponds to the folder structure org/example or full path /sample/directory/org/example) then you must ensure that you add an URL similar to the following:
YourClass::class.java.classLoader.getResource("")
and not:
YourClass::class.java.classLoader.getResource("org.example")
// nor:
YourClass::class.java.classLoader.getResource("org/example")
You basically require the "base" directory (in the example /sample/directory or from the view of the classloader just "")) where to lookup the packages and not the package itself. If you would supply one of the latter URLs, only classes that are in the default package (within /sample/directory/org/example) would actually be found, which however is a rather uncommon setup.

Robot Framework: Populating parameters based off of a robot.properties file?

I am attempting to mock-up a 'robot.properties' file to be utilized within my test cases with the Robot Framework. Inside my robot.properties file it contains things like for example:
project.username=stackoverflow
inside my test case file I have tried several times to 'import' the robot.properties file via adding within Settings: Resource ../path/to/properties and etc (see directory structure below), but when I attempt to pass 'project.username' as an argument to a test it passes it as the literal string value 'project.username' and not the value 'stack overflow'. I am new to Robot, I have implemented this in other languages like Java/C#, but I fully assume that the import is preventing me from accessing my value. Any help would be greatly appreciated, unfortunately this way of driving testing isn't really referenced much online that I can find.
Dir Structure:
Tests/Acceptance/MyTestCase.robot
Tests/robot.properties
If I try Library ../robot.properties I get:
"Import by filename is not supported"
If I try Resource ../robot.properties I get:
"Unsupported file format .properties"
Robot framework doesn't support a ".properties" file.
One solution is to use a variable file, which lets you define variables in python. Since you want to use dot notation, one way is to create a class and define your variables as properties of the class. The variable file can then make an instance of that class as a variable, and you can use extended variable syntax to access the variables.
The advantage to using a variable file over a plain text file is that you can create variables dynamically by calling other python functions. As a simple example, you could create a variable called "now" that contains the current date, or "host" that is the hostname of the machine running the test.
Example:
properties.py
import platform
class Properties(object):
username = "stackoverflow"
password = "SuperSecret!"
hostname = platform.uname()[1]
properties = Properties()
example.robot
*** Settings ***
Variables properties.py
Suite Setup log running on ${properties.hostname}
*** Test Cases ***
Example
should be equal ${properties.username} stackoverflow

Resources