How can I create a config file with unique only one unique property?
Or are there any loop for checking the config file where I find a duplicated name property value and it gives an exception?
[NAME+TIMESTAMP]
Name=UNIQUE NAME
Property=something
Property1=something1
Property2=something2
[NAME+TIMESTAMP]
Name=UNIQUE NAME
Property=something
Property1=something1
Property2=something2
Due to configParser being dict-like in most things, what we can do here is use the key of the different code-blocks to make sure that there are unique blocks.
Here is a simple test to show it in action:
import configparser
class Container:
configs=[] # keeps a list of all initialized objects.
def __init__(self, **kwargs):
for k,v in kwargs.items():
self.__setattr__(k,v) # Sets each named attribute to their given value.
Container.configs.append(self)
# Initializing some objects.
Container(
Name="Test-Object1",
Property1="Something",
Property2="Something2",
Property3="Something3",
)
Container(
Name="Test-Object2",
Property1="Something",
Property2="Something2",
Property3="Something3",
)
Container(
Name="Test-Object2",
Property1="Something Completely different",
Property2="Something Completely different2",
Property3="Something Completely different3",
)
config = configparser.ConfigParser()
for item in Container.configs: # Loops through all the created objects.
config[item.Name] = item.__dict__ # Adds all variables set on the object, using "Name" as the key.
with open("example.ini", "w") as ConfigFile:
config.write(ConfigFile)
In the above example, I create three objects that contain variables to be set by configparser. However, the third object shares the Name variable with the second Object. That means that the third one will "overwrite" the second while writing the .ini file.
example.ini:
[Test-Object1]
name = Test-Object1
property1 = Something
property2 = Something2
property3 = Something3
[Test-Object2]
name = Test-Object2
property1 = Something Completely different
property2 = Something Completely different2
property3 = Something Completely different3
Related
I'm trying to figure it out a way to create a namedtuple with variable fields depending on the data you receive, in my case, I'm using the data from StatCounter and not on all the periods are the same browsers. I tried this way but it is a bit ugly and I'm sure there is a better way to achieve it.
def namedtuple_fixed(name: str, fields: List[str]) -> namedtuple:
"""Check the fields of the namedtuple and changes the invalid ones."""
fields_fixed: List[str] = []
for field in fields:
field = field.replace(" ", "_")
if field[0].isdigit():
field = f"n{field}"
fields_fixed.append(field)
return namedtuple(name, fields_fixed)
Records: namedtuple = namedtuple("empty_namedtuple", "")
def read_file(file: str) -> List["Records"]:
"""
Read the file with info about the percentage of use of various browsers
"""
global Records
with open(file, encoding="UTF-8") as browsers_file:
reader: Iterator[List[str]] = csv.reader(browsers_file)
field_names: List[str] = next(reader)
Records = namedtuple_fixed("Record", field_names)
result: List[Records] = [
Records(
*[
dt.datetime.strptime(n, "%Y-%m").date()
if record.index(n) == 0
else float(n)
for n in record
]
)
for record in reader
]
return result
The "namedtuple_fixed" function is to fix the names that have invalid identifiers.
Basically, I want to create a named tuple that receives a variable number of parameters, depending on the file you want to analyze. And if it's with type checking incorporated (I mean using NamedTuple from the typing module), much better.
Thanks in advance.
This solves my problem, but just partially
class Record(SimpleNamespace):
def __repr__(self):
items = [f"{key}={value!r}" for key, value in self.__dict__.items()]
return f"Record({', '.join(items)})"
Using the types.SimpleSpace documentation
And it can cause problems, like for example if you initiallize a Record like the following:
foo = Record(**{"a": 1, "3a": 2})
print(foo.a) # Ok
print(foo.3a) # Syntax Error
I'm writing a package that imports audio files, processes them, plots them etc., for research purposes.
At each stage of the pipeline, settings are pulled from a settings module as shown below.
I want to be able to update a global setting like MODEL_NAME and have it update in any dicts containing it too.
settings.py
MODEL_NAME = 'Test1'
DAT_DIR = 'dir1/dir2/'
PROCESSING = {
"key1":{
"subkey2":0,
"subkey3":1
},
"key2":{
"subkey3":MODEL_NAME
}
}
run.py
import settings as s
wavs = import_wavs(s.DAT_DIR)
proc_wavs = proc_wavs(wavs,s.PROCESSING)
Some of the settings dicts I would like to contain MODEL_NAME, which works fine. The problem arises when I want to change MODEL_NAME during runtime. So if I do:
import settings as s
wavs = import_wavs(s.DAT_DIR)
s.MODEL_NAME='test1'
proc_wavs1 = proc_wavs(wavs,s.PROCESSING)
s.MODEL_NAME='test2'
proc_wavs2 = proc_wavs(wavs,s.PROCESSING)
But obviously both the calls so s.PROCESSING will contain the MODEL_NAME originally assigned in the settings file.
What is the best way to have it update?
Possible solutions I've thought of:
Store the variables as a mutable type, then update it e.g.:
s.MODEL_NAME[0] = ["test1"]
# do processing things
s.MODEL_NAME[0] = ["test2"]
Define each setting category as a function instead, so it is rerun on
each call e.g.:
MODEL_NAME = 'test1' ..
def PROCESSING():
return {
"key1":{
"subkey2":0,
"subkey3":1
},
"key2":{
"subkey3":MODEL_NAME
}
}
Then
s.MODEL_NAME='test1'
proc_wavs1 = proc_wavs(wavs,s.PROCESSING())
s.MODEL_NAME='test2'
proc_wavs1 = proc_wavs(wavs,s.PROCESSING())
I thought this would work great, but then it's very difficult to
change any entries of the functions during runtime eg if I wanted to
update the value of subkey2 and run something else.
Other thoughts maybe a class with an update method or something, does anyone have any better ideas?
You want to configure generic and specific settings structured in dictionaries for functions that perform waves analysis.
Start by defining a settings class, like :
class Settings :
data_directory = 'path/to/waves'
def __init__(self, model):
self.parameters= {
"key1":{
"subkey1":0,
"subkey2":0
},
"key2":{
"subkey1":model
}
}
# create a new class based on model1
s1 = Settings('model1')
# attribute values to specific keys
s1.parameters["key1"]["subkey1"] = 3.1415926
s1.parameters["key1"]["subkey2"] = 42
# an other based on model2
s2 = Settings('model2')
s2.parameters["key1"]["subkey1"] = 360
s2.parameters["key1"]["subkey2"] = 1,618033989
# load the audio
wavs = openWaves(Settings.data_directory)
# process with the given parameters
results1 = processWaves(wavs,s1)
results2 = processWaves(wavs,s2)
Is it possible?
Something in the lines of :
import win32com.client
ProgID = "someProgramID"
com_object = win32com.client.Dispatch(ProgID)
for methods in com_object:
print methods
I got the com_object.__dict__, which lists:
[_oleobj_, _lazydata_, _olerepr_, _unicode_to_string_, _enum_, _username_, _mapCachedItems_, _builtMethods_]
Most are empty, except:
_oleobj_ (PyIDispatch)
_lazydata_ (PyITypeInfo)
_olerepr_ (LazyDispatchItem instance)
_username_ (<unknown>)
But I don't know how to access anything on those types.
For those who find the accepted answer not working (look here for the reasons) - there's still a way to get objects having a _prop_map_get_ attribute (a dict that holds object's fields as keys). You just have to create the main app object with win32com.client.gencache.EnsureDispatch().
Here's a convenience function I wrote that lists fields and methods of a passed COM object created that way:
from inspect import getmembers
def print_members(obj, obj_name="placeholder_name"):
"""Print members of given COM object"""
try:
fields = list(obj._prop_map_get_.keys())
except AttributeError:
print("Object has no attribute '_prop_map_get_'")
print("Check if the initial COM object was created with"
"'win32com.client.gencache.EnsureDispatch()'")
raise
methods = [m[0] for m in getmembers(obj) if (not m[0].startswith("_")
and "clsid" not in m[0].lower())]
if len(fields) + len(methods) > 0:
print("Members of '{}' ({}):".format(obj_name, obj))
else:
raise ValueError("Object has no members to print")
print("\tFields:")
if fields:
for field in fields:
print(f"\t\t{field}")
else:
print("\t\tObject has no fields to print")
print("\tMethods:")
if methods:
for method in methods:
print(f"\t\t{method}")
else:
print("\t\tObject has no methods to print")
For an Excel object created with win32com.client.gencache.EnsureDispatch("Excel.Application") its output would be:
Members of 'Excel.Application' (Microsoft Excel):
Fields:
ActiveCell
ActiveChart
ActiveDialog
ActiveEncryptionSession
...
Workbooks
WorksheetFunction
Worksheets
_Default
Methods:
ActivateMicrosoftApp
AddChartAutoFormat
AddCustomList
Calculate
...
Union
Volatile
Wait
Just found how to get most of the methods:
Here's how:
import win32com.client
import pythoncom
ProgID = "someProgramID"
com_object = win32com.client.Dispatch(ProgID)
for key in dir(com_object):
method = getattr(com_object,key)
if str(type(method)) == "<type 'instance'>":
print key
for sub_method in dir(method):
if not sub_method.startswith("_") and not "clsid" in sub_method.lower():
print "\t"+sub_method
else:
print "\t",method
Here's a exemple output with ProgID = "Foobar2000.Application.0.7"
Output:
Playlists
Add
GetSortedTracks
GetTracks
Item
Load
Move
Remove
Save
Name
foobar2000 v1.1.13
ApplicationPath
C:\Program Files (x86)\foobar2000\foobar2000.exe
MediaLibrary
GetSortedTracks
GetTracks
Rescan
Minimized
True
Playback
FormatTitle
FormatTitleEx
Next
Pause
Previous
Random
Seek
SeekRelative
Start
Stop
ProfilePath
file://C:\Users\user\AppData\Roaming\foobar2000
To list the attributes of an object you can use the dir() function. This is a built in function of python and does not need to be imported.Try something like:
print dir(object)
To see the attributes of the object.
I have a django application that is utilizing a third party API and needs to receive several arguments such as client_id, user_id etc. I currently have these values labeled at the top of my file as variables, but I'd like to store them in an object instead.
My current set up looks something like this:
user_id = 'ID HERE'
client_id = 'ID HERE'
api_key = 'ID HERE'
class Social(LayoutView, TemplateView):
def grab_data(self):
authenticate_user = AuthenticateService(client_id, user_id)
I want the default values set up as an object
SERVICE_CONFIG = {
'user_id': 'ID HERE',
'client_id': 'ID HERE'
}
So that I can access them in my classes like so:
authenticate_user = AuthenticateService(SERVICE_CONFIG.client_id, SERVICE_CONFIG.user_id)
I've tried SERVICE_CONFIG.client_id, and SERVICE_CONFIG['client_id'], as well as setting up the values as a mixin but I can't figure out how to access them any other way.
Python is not Javascript. That's a dictionary, not an object. You access dictionaries using the item syntax, not the attribute syntax:
AuthenticateService(SERVICE_CONFIG['client_id'], SERVICE_CONFIG['user_id'])
You can use a class, an instance, or a function object to store data as properties:
class ServiceConfig:
user_id = 1
client_id = 2
ServiceConfig.user_id # => 1
service_config = ServiceConfig()
service_config.user_id # => 1
service_config = lambda:0
service_config.user_id = 1
service_config.client_id = 2
service_config.user_id # => 1
Normally using a dict is the simplest way to store data, but in some cases higher readability of property access can be preferred, then you can use the examples above. Using a lambda is the easiest way but more confusing for someone reading your code, therefore the first two approaches are preferable.
I have following module root_file.py. This file contains number of blocks like.
Name = {
'1':'a'
'2':'b'
'3':'c'
}
In other file I am using
f1= __import__('root_file')
Now the requirement is that I have to read values a,b,c at runtime using variables like
for reading a
id=1
app=Name
print f1[app][id]
but getting error that
TypeError: unsubscriptable object
How about
import root_file as f1
id = 1
app = 'Name'
print getattr(f1, app)[id] # or f1.Name[id]
Uh, well, if I understand what you are trying to do:
In root_file.py
Name = {
'1':'a', #note the commas here!
'2':'b', #and here
'3':'c', #the last one is optional
}
Then, in the other file:
import root_file as mymodule
mydict = getattr(mymodule, "Name")
# "Name" could be very well be stored in a variable
# now mydict eqauls Name from root_file
# and you can access its properties, e.g.
mydict['2'] == 'b' # is a True statement