pythonloggingwandb

Can I pass 'wandb' object to another class in python?


I have written a modular code and I wanted to pass a wandb object to a class which has been written in another .py file. I instantiated a wandb object using:

import wandb 
exp_name = "expriment name"
run = wandb.init(config = wandb.config, project= exp_name, entity="username")

at the top of the main.py file. Now whenever I need to log anything I use run.log({'Accuracy/train': 100.0 * n_class_corrected / total_class_samples}, step=iteration) and it works when I call it within the main.py or if I pass it to a function. But I am still wondering when I pass it to a class defined in another .py file it is not going to log anything. Overall my question is how should I pass a wandb object to another class which is in another .py file. Is there any consideration that I should pay attention to?


Solution

  • You can pass it around just as you would pass any object. You can also just call import wandb in the other file, and rather than passing around the object you can call wandb.log in that file. W&B will be smart enough to log it to the same run.

    file_1: 
    from file_2 import something_else
    import wandb
    wandb.init(...)
    wandb.log(...)
    something_else()
    
    file_2:
    import wandb
    
    def something_else():
        wandb.log({'something_else': 123})